Rahul SK
Rahul SK

Reputation: 432

regex pattern matcher fails

I want to know why my regex pattern matcher below fails.

I have included ?A-Za-z0-9 to include chars and numbers

System.out.print(Pattern.compile("[?A-Za-z0-9]").matcher("aa22Aa?").matches());

Upvotes: 1

Views: 171

Answers (2)

Yousaf
Yousaf

Reputation: 29354

?A-Za-z0-9 will only match a single occurrence of a particular character defined in the set

You need to add + quantifier to the pattern so that one or more of the characters match

[?A-Za-z0-9]+

Instead of calling .compile() function to compile the pattern and then calling .matcher() function to create a Matcher, you can use .matches() function of Pattern class to compile the pattern and match it with the string.

System.out.print(Pattern.matches("[?A-Za-z0-9]+", "aa22Aa?"));

Edit:

As rightly pointed out by @Andreas, you could also use .matches() function of String class

System.out.print("aa22Aa?".matches("[?A-Za-z0-9]+"));

Upvotes: 1

user4910279
user4910279

Reputation:

Try "[?A-Za-z0-9]+".

Upvotes: 0

Related Questions