Reputation: 3085
I need to check if the string provided by the user starts with abc and ends with de with 4 characters in between like
"abc<4 characters>de".
I tried using pattern ("^abc.*(4)de$")
But it fails for the 4 characters in middle. Is there any problem with pattern.
Upvotes: 0
Views: 101
Reputation: 62874
Change the ()
brackets with {}
^abc.{4}de$
which means that the matching word should start with abc and end with de and in between there should be excactly 4 characters.
A simpler solution is just to place a .
between the start
and the end
pattern to describe that there should be exactly four characters:
^abc....de$
Upvotes: 2
Reputation: 10034
Modify RegEx to following
Pattern p = Pattern.compile("^abc.{4}de$");
Matcher m = p.matcher("abc11111de");
boolean b = m.matches();
System.out.println(b);
Upvotes: 1
Reputation: 328785
To say you need exactly four characters, you can use one of those:
"^abc.{4}de$"
"^abc....de$"
Upvotes: 3
Reputation: 382404
Use this regular expression :
^abc.{4}de$
.{4}
is exactly what it seems : any character (.
) exactly 4 times.
Upvotes: 1