regex that must check the string contains a specific word

advertisements

I wrote a regex which should check does string contains word 'Page' and after it any number This is code:

public static void main(String[] args) {
    String str1 = "12/15/14  7:01:44    Page   10 ";
    String str2 = "12/15/14  7:01:44    Page    9 ";
    System.out.println(containsPage(str2));
}

private static boolean containsPage(String str) {
    String regExp = "^.*Page[ ]{1,}[0-9].$";
    return Pattern.matches(regExp, str);
}

Result: str1: false, str2:true

Can you help me what is wrong?


Change it to:

String regExp = "^.*Page[ ]{1,}[0-9]+.$";  //or \\d+
                                    ↑

[0-9] matches 9 in the second example, and . matches the space.

In the first example, [0-9] matches 1, . matches 0 and remained space isn't matched. Note that ^ and $ are not really needed here.

Your regex can be simplified to:

String regExp = ".*Page\\s+\\d+.";