Regular expression to match exact character and numbers

I want to match a string, which can be either KH1 , or KH2 or ... KH99 .

I did,

 public class Test1 { public static void main(String[] args) { String name = "KH1"; if(name.matches("[[K][H][1-9][0-9]]") || name.matches("[[K][H][1-9]]")){ System.out.println("VALID NAME"); }else{ System.out.println("INVALID NAME"); } } } 

This does not work. I get INVALID NAME .

What is the right way to do this?

+6
source share
3 answers

Remove the outer square brackets:

 if(name.matches("[K][H][1-9][0-9]?")){ 

Watch the IDEONE demo

The problem is that you included the entire pattern in the character class with an external [...] , and all the characters inside (except the brackets) were treated as single literals, and the whole expression could correspond to only 1 character.

Speaking of optimization: rotation is not required here, since you can apply ? quantifier to class [0-9] to make it optional. ? matches 0 or 1 occurrence of the previous subpattern.

Also note that [K][H] makes sense if you plan to add additional parameters to character classes, otherwise you could use

 if(name.matches("KH[1-9][0-9]?")){ 

or

 if(name.matches("KH[1-9]\\d?")){ 

\d is an abbreviated class that matches a digit.

+8
source

First of all, these outer square brackets are incorrect. Delete them. Secondly, your regular expression can be simplified. You do not need two separate expressions, and you do not need to enclose single characters K and H in a character class. Try:

 KH[1-9][0-9]? 

This will correspond to the literal characters KH , followed by numbers from 1 to 9 and optionally another digit from 0 to 9 - illustrated by the following legal lines:

 KH1 KH2 ... KH8 KH9 KH10 KH11 ... KH18 KH19 KH20 KH21 ... KH98 KH99 
+4
source

You can use one regular expression.

 if(name.matches("KH(?:[1-9]\\d|[1-9])")) { 
+3
source

All Articles