I want to match a string that 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");
}
}
}
It doesnot work. I get INVALID NAME
.
What is the correct way for this?
Remove the outer square brackets:
if(name.matches("[K][H][1-9][0-9]?")){
See IDEONE demo
The issue is that you enclosed the whole pattern into a character class with outer [...]
, and all the symbols inside (except the brackets) were treated as single literal symbols, and the whole expression could only match 1 character.
Talking about optimizations: the alternation is not really necessary here since you can apply ?
quantifier to the [0-9]
class to make it optional. ?
matches 0 or 1 occurrence of the preceding subpattern.
Also note that [K][H]
makes sense if you plan to add more options into the character classes, otherwise you might as well use
if(name.matches("KH[1-9][0-9]?")){
or
if(name.matches("KH[1-9]\\d?")){
The \d
is a shorthand class that matches digit(s).
First of all those outer square brackets are incorrect. Remove them. Second of all, your regular expression can be simplified a lot. You do not need two separate expressions, nor do you need to enclose the single characters K
and H
in a character class. Try:
KH[1-9][0-9]?
This will match the literal characters KH
, followed by a digit 1 through 9, and optionally another digit 0 through 9 - illustrated by the following legal strings:
KH1
KH2
...
KH8
KH9
KH10
KH11
...
KH18
KH19
KH20
KH21
...
KH98
KH99
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With