Jules L
Jules L

Reputation: 133

How to check with a regex if a String contains two letters and a variable amount of digits in Java?

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;
}

Upvotes: 1

Views: 1290

Answers (3)

Chris
Chris

Reputation: 3338

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.

Upvotes: 0

Ryan Schaefer
Ryan Schaefer

Reputation: 3120

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.

Upvotes: 1

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59960

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

Upvotes: 1

Related Questions