简体   繁体   中英

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

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 ^[az]{2}\\d*-abc

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

check regex demo

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM