Mahendran
Mahendran

Reputation: 2243

Question mark in regular expression matching is not working

I am new to regular expressions. I thought that this would return matched succesfully, but it does not. Why is that so?

String myString = "SUB_HEADER5_LABEL";
if (myString.matches(Pattern.quote("SUB_HEADER?_LABEL")))
{
    System.out.println("matched succesfully");
}

Upvotes: 0

Views: 292

Answers (1)

jlordo
jlordo

Reputation: 37813

Pattern.qoute() will create a Pattern that only matches exactly the given String. you need

if (myString.matches("SUB_HEADER\\d_LABEL"))

If you expect the number to exceed 9, add the + quantifier like

if (myString.matches("SUB_HEADER\\d+_LABEL"))

if you want to match a digit where you have ? (wich means one or zero R in your case, because it's a quantifier). you need to replace it with [0-9] or \\d.

Upvotes: 4

Related Questions