Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to Match Exact Character and Numbers

Tags:

java

regex

java-8

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?

like image 588
Rajkishan Swami Avatar asked Aug 20 '15 06:08

Rajkishan Swami


2 Answers

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).

like image 152
Wiktor Stribiżew Avatar answered Oct 14 '22 16:10

Wiktor Stribiżew


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
like image 26
lc. Avatar answered Oct 14 '22 15:10

lc.