Click here to Skip to main content
15,867,939 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Java
System.out.println(Pattern.matches("[amn]?", "a"));


This statement returns true.

But

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


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


These statements returns false.

Why ?

What I have tried:

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 ?
Posted
Updated 28-Sep-16 21:41pm

The problem is that "?" means just that: "0 or 1 repetition of the preceding item"
Which means it's optional.
Take the "integer number" regex:
^[+-]?\d+$

What that says is "the whole string consists of at least one digit, which may be preceded by a single plus or minus"
So it matches:
C#
0
1
123456789
-1
+0
But it won;t match
A
++0
+-999
Your regex matches "zero or one character from 'a', 'm', or 'n'" - which means that it matches anything at all!
if it was written as
^[amn]?$
Then it would match
a
n
m
But wouldn't match
b
c
9
Hello!

Get a copy of Expresso[^] - it's free, and it examines and generates Regular expressions.
 
Share this answer
 
Comments
CPallini 29-Sep-16 3:44am    
5.
In Pattern.matches("[amn]?", ...) the fragment [amn] means "any one character from the set {a, m, n}". So [amn]? should match exactly zero or one of those characters. In your second example, there are three that match, hence the false return. Bear in mind that the matches function "attempts to match the entire input against the pattern" (to paraphrase the documentation). Pattern.matches() is a weird beast indeed.
I am surprised at the third result, however. I don't have the ability to test it myself right now.
 
Share this answer
 

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