Lusi
Lusi

Reputation: 401

regex which should check string contains specified word

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?

Upvotes: 3

Views: 99

Answers (2)

Maroun
Maroun

Reputation: 95958

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+.";

Upvotes: 1

M A
M A

Reputation: 72844

Change the regex to the following:

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

so that it matches one or more digits (hence the [0-9]+).

You also don't need the boundary matchers (^ and $) since Pattern#matches would match the entire input string; and [ ]{1,} is equivalent to [ ]+:

String regExp = ".*Page +[0-9]+.";

Upvotes: 5

Related Questions