Skip to content
Advertisement

Regex match group not working even if .find() and matches() were already called

I’ve already tried adding the matcher.find() and matcher.matches() in order to query matching string values, but still its not working.

I am trying to have 3 group patterns to match, and for my example here, I want to match and find group 1 of pattern enclosed in the first round parenthesis.

JavaScript

Why is the grp1 not being retrieved?, afaik this code should work as I already called .find() or .matches() which is required for using .group() methods.

For reference, I’m trying to apply the accepted answer here that uses matcher.group(int) to match strings

Attached below is the code that I will have if I dont implement Java Match Group feature just like in the answer which is in link above, I would have at least 5 declaration for each patterns and matchers instead of just one Pattern and Matchers to determine what patterns matched.

JavaScript

Advertisement

Answer

Your pattern ^0\d{10})(^\d{10})(^63\d{10}) does not match, as it asserts the start of the string 3 times in a row followed by matching digits.

Instead you can use a match only instead of a capture group, and optionally match either 0 or 63 followed by 10 digits.

Using find() you can first check if there is a match, as find tries to find the next match and returns a boolean.

For a match only, you can use:

JavaScript
  • ^ Start of string
  • (?:0|63)? Optionally match 0 or 63
  • d{10} Match 10 digits
  • b A word boundary to prevent a partial word match

For example:

JavaScript

See a Java demo and a regex demo.

Using matches, the pattern should match the whole string, which is the case for the given example data.

JavaScript

EDIT

If you must have 3 capture groups, you can use an alternation between the groups and add a word boundary at the end:

JavaScript

The pattern matches:

  • ^ Start of string
  • (?: Non capture group
    • (0d{10}) Capture group 1, match 0 and 10 digits
    • | Or
    • (d{10}) Capture group 2, match 10 digits
    • | Or
    • (63d{10}) Capture group 3, match 63 and 10 digits
  • )b Close the non capture group a and add a word boundary

Regex demo

For example

JavaScript

See a Java demo

Advertisement