-1

I have a question about the the usage of non-capturing group (?:...).

\b4[0-9]{12}(?:[0-9]{3})\b
(?:\d[ -]*?){13,16}\b

In the first case, the string extracted would have 13 or 16 digits. Whether the last 3 digits appear or not is based on the condition of the string because of the parenthesis even if {3} in the parenthesis asks for exactly the 3 digits? In the second case, I tested the re and found that only digits were counted into the the length of the string. Dash and space is not counted into the length, although they are put in the same parenthesis in from the boundary of string length. Does anyone know the reason?

Thanks

elixenide
  • 42,388
  • 14
  • 70
  • 93
Lucy
  • 1

1 Answers1

0

You're mistaken. As written, the first one requires exactly 16 digits. You would need a ? after the non-matching group if you wanted to allow for a 13-digit number, like this: \b4[0-9]{12}(?:[0-9]{3})?\b.

As for the second one, the {13,16} applies to the entire group. Each match against that group can have zero or more spaces or dashes. I just explained this in detail in an answer to a very similar question (perhaps y'all are in the same class or something?):

(?:\d[ -]*?){13,16} - confused with the priority that is given in matching the pattern to the given regex

Community
  • 1
  • 1
elixenide
  • 42,388
  • 14
  • 70
  • 93
  • I've reviewed the answer in the link. Just one question about that. If the {13, 16} is applied to the entire group, then, the output of the regex has a length of 19 instead of 16, which violates the upper bound limit. Could you explain that? Should the dash be counted into the length of the string or not? – Lucy Apr 11 '16 at 18:26
  • @Lucy You're thinking about it the wrong way. Yes, dashes count as part of the length of the string, but the `{13,16}` does not limit the length of the string. It specifies the number of times that the entire group `(?:\d[ -]*?)` should match. That group matches any digit followed by zero or more spaces or dashes. So, you could have, for example, `401-2---3- - - - 4 - -- --- ----` etc., as long (1) there are 13-16 digits and only spaces or dashes between digits. You might find [this demo](https://regex101.com/r/qD3qE2/2) helpful. – elixenide Apr 11 '16 at 19:04
  • @ Ed Cottrell Now I undestand. Thank you! – Lucy Apr 11 '16 at 19:29