Skip to content
Advertisement

Java Regex: matches(pattern, value) returns true but group() fails to match

I have an odd problem with a regular expression in Java. I tested my Regex and my value here and it works. It says there are 3 groups (correct) the match for the first group (not group zero!) is SSS, the match for group 2 is BB and the match for group 3 is 0000. But my code below fails and I am quite at a loss why…

JavaScript

Here is a screenshot from the matching result of the above website: enter image description here

I’d be really grateful if anyone could point out the mistake I am making… On an additional note: Strangely enough, if I execute the following code true is returned which implies a match should be possible…

JavaScript

Advertisement

Answer

You need to call find() before group():

JavaScript

When you invoke matcher(value), you are merely creating a Matcher object that will be able to match your value. In order to actually scan the input, you need to use find() or lookingAt():

References:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement