Ganesh Ramachandran Ganesh Ramachandran - 1 year ago 92
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 ?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download