Click here to Skip to main content
15,912,507 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can anyone explain the the output


System.out.println(Pattern.matches("[amn]?", "a"));//true (a or m or n comes one time)
System.out.println(Pattern.matches("[amn]?", "am"));//false (a or m or n must come one time)  


What I have tried:

I am not able to understand why second statement is false. I am expecting it to be true because 'a' and 'm' are coming at least once
Posted
Updated 27-Dec-19 19:54pm
v2

1 solution

Pattern.matcher(String str) returns a Matcher that can find patterns in the String.
Pattern.matches(String str) tests if the entire String matches the pattern.

If you want to work with Regular expressions, get a copy of Expresso[^] - it's free, and it examines and generates Regular expressions.
It will tell you exactly what "[amn]?" means:
Any character in this class: [amn], zero or one repetitions

So a single character in the class will match as a whole string, but two characters can't.
Try: "[amn]*" instead.
 
Share this answer
 
v2
Comments
radhikay 28-Dec-19 2:20am    
In my question, both statements have Pattern.matches but why the second statement is false.? Both 'm' and 'n' are present in [amn]
OriginalGriff 28-Dec-19 2:36am    
Read the reply again ...
phil.o 28-Dec-19 5:50am    
Because of the 'zero or one repetition' specifier: "am" is two characters long, thus exceeds the limit.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900