ajay ajay
ajay ajay

Reputation: 1

Pattern match not matching

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

Answers (3)

Avinash Raj
Avinash Raj

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

Rakesh KR
Rakesh KR

Reputation: 6527

Try with

String.matches("25\\d*")

enter image description here

OR you cau use

String.startsWith("25")

Upvotes: 1

Maroun
Maroun

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

Related Questions