0

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.

4 Answers 4

3

To say you need exactly four characters, you can use one of those:

"^abc.{4}de$"
"^abc....de$"
Sign up to request clarification or add additional context in comments.

Comments

2

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$

Comments

1

Use this regular expression :

^abc.{4}de$

.{4} is exactly what it seems : any character (.) exactly 4 times.

Comments

1

Modify RegEx to following

Pattern p = Pattern.compile("^abc.{4}de$");
         Matcher m = p.matcher("abc11111de");
         boolean b = m.matches();
         System.out.println(b);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.