Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to find special characters in Java [closed]

Tags:

java

regex

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?

like image 698
Shih-En Chou Avatar asked Sep 25 '12 15:09

Shih-En Chou


2 Answers

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

like image 161
Sri Harsha Chilakapati Avatar answered Oct 12 '22 09:10

Sri Harsha Chilakapati


Use String.matches(). Read the Javadocs for supported syntax.

like image 2
Dave Avatar answered Oct 12 '22 09:10

Dave