1

I have this very specific use case where I want to check if a String contains 2 lower case letters, concatenated by a variable number of digits and a "-abc".

The "-abc" part must not be variable and should always be "-abc". So in the end only the number of digits can be variable.

It can be like this :

ab123-abc

or like this :

ab123456-abc

or even like this :

cd5678901234-abc

I have tried the following but it does not work :

if (s.toLowerCase().matches("^([a-z]{2})(?=.*[0-9])-abc")) {
    return true;
}

3 Answers 3

1

You are close instead of (?=.*[0-9]) use \d* to match zero or more digits or \d+ to match one or more digits, so you can use this regex ^[a-z]{2}\d*-abc

if(s.toLowerCase().matches("^[a-z]{2}\\d*-abc")){
   return true;
}

check regex demo

Sign up to request clarification or add additional context in comments.

2 Comments

Works like a charm. Thank you.
Just checked the regex demo website, very handy.
1

You don't need to do the if statement. Just do:

s.toLowerCase().matches("^[a-z]{2}\d+-abc")

as it already returns true. Notice my answer is different from the one above because it requires a digit between the letters and -abc.

1 Comment

Yeah, the if statement was to mainly to be explicit, in my code the return statement is : return s.toLowerCase().matches("^[a-z]{2}\\d+-abc");
0

The regex that you want to use is:

 /^[a-z]{2}[0-9]+-abc$/i
                ^ 
               "+" means "at least 1"

This will match exactly two letters, at least one number, and a trailing -abc.

You can also use the Pattern class to create a single Regex object. You can then use the Pattern.CASE_INSENSITIVE flag to ignore case.

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.