Reputation: 432
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
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?"));
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