5

Here is my issue. I have this:

String data = "java.awt.Color[r=168,g=228,b=160]" //example this changes.
Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher(data);
if(m.matches()){
    ....
}

However, it is not matching. Why is that? I am trying to retrieve the numbers inside brackets.

What should I try?

pb2q
  • 58,613
  • 19
  • 146
  • 147
Scott Deutsch
  • 637
  • 1
  • 8
  • 24

6 Answers6

14

Matcher.matches() matches the complete string. You can use Matcher.find to match the individual integers:

while (m.find()) {
  System.out.println(m.group(1));
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276
4

Matcher.matches tells you if your regex matches the entire string. Your string isn't all digits. It contains letters, dots, equal signs, and square brackets. So you matcher doesn't match.

You want Matcher.find(). That searches for partial matches. Matcher.group then allows you to retrieve the matched portion of the input string.

Tim Pote
  • 27,191
  • 6
  • 63
  • 65
4

The matches method will attempt to match the regex against the entire input.

Use a combination of the the find and group methods method to find and use matches within the input:

while (m.find())
    System.out.println(m.group());
pb2q
  • 58,613
  • 19
  • 146
  • 147
3

Note that the Matcher.matches() method attempts to match against the entire string.

You want to use Matcher.find() instead.

maerics
  • 151,642
  • 46
  • 269
  • 291
1

Because your regex doesn't match the string, there are other characters before (and after) the \d matches after all.

Tim Lamballais
  • 1,056
  • 5
  • 10
1

matches() method attempts to match the whole string, but you need just digit occurrences in it. You need to use find() method and you might need to use while operator instead of if because it shifts matcher to next match occurrence.

Sled
  • 18,541
  • 27
  • 119
  • 168
Alex Gorbunov
  • 239
  • 3
  • 8