user1035795
user1035795

Reputation: 93

Java 1.7 String class matches method returns false when it should be true

String s = "Remediation Release 16  - Test Status Report_04032014.xlsx";

s.matches("([^\\s]+(\\.(?i)(xlsx))$)"); // returns false

I've tried the exmaple on http://regex101.com/ and its says the match is true.

Is there some nuance of the matches method I am missing

Upvotes: 0

Views: 124

Answers (2)

Mena
Mena

Reputation: 48444

You're missing the whole text in between the start and file extension.

Try with:

String s = "Remediation Release 16  - Test Status Report_04032014.xlsx";
//                                    | "Remediation" ... to ... "Report_04032014"
//                                    | is matched by ".+"
System.out.println(s.matches("([^\\s]+.+(\\.(?i)(xlsx))$)"));

Output

true

As matches matches the whole text:

  • [^\\s] will match the beginning of your input.
  • .+ will match the file name
  • (\\.(?i)(xlsx))$) will match the dot + extension, case-insensitive, followed by end of input

To prove this:

//                           | removed outer group
//                           |      | added group 1 here for testing purposes
//                           |      |   | this is now group 2
//                           |      |   |               | removed outer group
Pattern p = Pattern.compile("[^\\s]+(.+)(\\.(?i)(xlsx))$");
Matcher m = p.matcher(s);
while (m.find()) {
    System.out.println("Group 1: " + m.group(1) + " | group 2: " + m.group(2));
}

Output

Group 1:  Release 16  - Test Status Report_04032014 | group 2: .xlsx

Also as demonstrated, you don't need the outer parenthesis in your initial matches argument.

Upvotes: 0

Sabuj Hassan
Sabuj Hassan

Reputation: 39443

In java matches() does perform the matching over the whole string. So you have to use .* at the begging of your regex.

s.matches(".*([^\\s]+(\\.(?i)(xlsx))$)");
           ^^ here

Upvotes: 2

Related Questions