Regex to find special characters in Java

java, regex

Solution

Try this.

Pattern regex = Pattern.compile("[$&+,:;=?@#|]");
Matcher matcher = regex.matcher("123=456");
if (matcher.find()){
    // Do something
}

EDIT: `matches()` checks all the string and `find()` finds it in any part of the string.

A link: `http://docs.oracle.com/javase/tutorial/essential/regex/index.html`

Problem

I can use ``` var regex = /[$&+,:;=?@#|]/; if(elem.match(regex)) { // do something } ``` to find whether there is any special characters in string in Javascript. How can I use the similar regular expression in Java? I have tried: ``` str.match("\\="); // return false ``` For example: ``` String str = "123=456"; ``` I tried to detect "=" in str. That did not work. What am I doing wrong?

Original source