Reputation: 1
I am trying to match a pattern for digits. First two digits would be 2
and 5
. There may be more digits e.g. 25
, 253
, 2599
, 255
For this I have written like
Pattern myPattern = Pattern.compile("[2][5]*");
if(myPattern.matcher("25").matches()) {
}
if(myPattern.matcher("253").matches()) {
}
but it always returns false
. I am not sure what is wrong with my pattern.
Upvotes: 0
Views: 78
Reputation: 174706
You could try the below regex,
"25\\d*"
What's wrong with your regex [2][5]*
is, first it matches 2
then it matches only the number 5 zero or more times. But \d*
matches any digit(0-9) zero or more times.
System.out.println("25".matches("25\\d*"));
System.out.println("253".matches("25\\d*"));
Upvotes: 2
Reputation: 6527
Try with
String.matches("25\\d*")
OR you cau use
String.startsWith("25")
Upvotes: 1
Reputation: 95968
While you can solve this by using the regex suggested by @avinashraj, I want to suggest a better solution using String#startsWith
, you don't really need regex here:
if(myString.startsWith("25")) {
//...
}
Upvotes: 3