Ganesh Ramachandran Ganesh Ramachandran - 3 months ago 14
Java Question

How does java quantifier "?" work?

System.out.println(Pattern.matches("[amn]?", "a"));

This statement returns true.


System.out.println(Pattern.matches("[amn]?", "amn"));

System.out.println(Pattern.matches("[amn]?", "adef"));

These statements returns false.

Why ?

My understanding about regex quantifier "?" is this.

Regex: X?

Description: X occurs once or not at all

So the statement "[amn]?" "amn" should return true because a,m,n occurs once.
And similarly in "[amn]?" "adef" a occurs only once and m and n do not occur at all.

Where am I going wrong ?


The regex [amn]? matches any string which consists of either a , m or n and nothing else. Such as "a", which fulfills this condition.

amn and adef, however, start with one of these letters, but continue so that the "once or not at all" rule is not fulfilled.