mnish
mnish

Reputation: 3897

use regex to match strings containing "(number)" pattern at the end

I use the following pattern to check if it matches with this kind of strings:

words that contains any characters and ends with (positive numbers)

assertEquals(true, str.matches("[\\w+ ]*\\(\\d\\)")); 

the assertion returns true for the following situations:

str = "one two three (1)";
str = "one 2 three to 400 (4)";
str = " begins with space (4)";
str = "(4)";

But it fails on the following:

str = "one (two) three (1)";

Any suggestions?

Thank you!

Upvotes: 1

Views: 88

Answers (2)

Marchev
Marchev

Reputation: 1370

The following regex would match words that contain any character and end with a (positive number):

.*\([1-9]+\)

Two things to note here:

  1. The regex that is provided in the original post uses \w which matches word characters: [a-zA-Z0-9_]
  2. \d matches digits. This means that you regex would also match zero which is neither a positive, nor a negative number. In case you want positive numbers only then you should use [1-9]+

Upvotes: 0

M A
M A

Reputation: 72854

You need to include parentheses in the character class -- \w is equivalent to [a-zA-Z_0-9] so it doesn't cover them. Also the quantifier + matches the literal + when placed in the character class, so it should be set outside the square brackets. But since you want to also match the case of (4), then it should be * instead:

assertEquals(true, str.matches("[\\w ()]*\\(\\d\\)"));

More generally, according to your requirement "words that contains any characters and ends with (positive numbers)", the following would be more suitable:

assertEquals(true, str.matches(".*\\(\\d\\)$"));

(. matches any character; $ marks the end of a line)

Upvotes: 2

Related Questions