Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java simple regular expression

Tags:

java

regex

I want to specify a regex that finds if there are any non letter non number chars in a String.

Basically I want it to accept [a-z][A-Z][0-9] in any order any combination..i.e "2a4A44awA" should be valid.

How can I do this?

like image 496
mixkat Avatar asked Feb 18 '11 13:02

mixkat


2 Answers

Instead of:

[a-z][A-Z][0-9] 

Match with:

[a-zA-Z0-9]+

From the API:

Greedy quantifiers
X?  X, once or not at all
X*  X, zero or more times
X+  X, one or more times
X{n}    X, exactly n times
X{n,}   X, at least n times
X{n,m}  X, at least n but not more than m times
like image 72
jzd Avatar answered Sep 22 '22 16:09

jzd


String s = ".... ;

System.out.println(s.matches(".*[^a-zA-z0-9].*"));

returns true if illegal character is present.

Edit: But the first answer from jzd is better:

s.matches("[a-zA-Z0-9]+");

Returns true if illegal character not present, ie the string is good.

like image 25
Richard H Avatar answered Sep 23 '22 16:09

Richard H