mehdi
mehdi

Reputation: 686

My regex does not work

This code does not return the correct result:

Pattern p=Pattern.compile("^[y]{1,4}$|^[m]{1,4}$|^[d]{1,4}$");

String text1="yyyy";
String text2="mmm";

Matcher m=p.matcher(text);
boolean b=m.find();
System.out.println(String.valueOf(b));

m=p.matcher(text2);
b=m.find();
System.out.println(String.valueOf(b));

The line System.out.println(String.valueOf(b)); prints false I want it to return true. Does anyone see what's wrong with the code?

Upvotes: 0

Views: 199

Answers (1)

KARASZI István
KARASZI István

Reputation: 31467

A simpler regex could be:

^(y{1,4}|m{1,4}|d{1,4})$

UPDATE1: I've checked your regex as well, and it's syntactically correct but maybe the Java regex engine does not like it.

UPDATE2: I even checked your Java code and it works for me with only one exception that in the first part it's text1 instead of text what you've typed.

It prints out true for me in my JVM, so the problem is probably not with your regex.

Upvotes: 4

Related Questions