3

I do not know why there are 2 matches found aside from the input using this regex, when I expected only 1 match.

preg_match(/_(\d(-\d){0,3})\./,$str,$matches);

on this file string format name_A-B-C-D.ext.

I would expect to get a single match like this:

Example A
[0] => name_A-B-C-D.ext  
[1] => A-B-C-D

Example B
[0] => name_A-B-C.ext  
[1] => A-B-C

But this is the result I get:

Example A
[0] => name_A-B-C-D.ext  
[1] => A-B-C-D
[2] => -D

Example B
[0] => name_A-B-C.ext  
[1] => A-B-C
[2] => -C

I only wish to capture A up to D if its preceded with a hyphen. This code is usable and I can simply ignore the 2nd match, but I would like to know why its there. I can only assume it has something to do with my two capture groups. Where is my error ?

Kim
  • 2,747
  • 7
  • 41
  • 50

3 Answers3

8

Yes, you get two captures because you have two capturing groups in your regular expression.

To avoid the unwanted capture you could use a non-capturing group (?:...):

/_(\d(?:-\d){0,3})\./
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
1

I can only assume it has something to do with my two capture groups.

Your assumption is correct

Where is my error ?

There is no error, everything is behaving as expected.

user229044
  • 232,980
  • 40
  • 330
  • 338
0

You have to groups in your RE, so you get 2 matches. What is surprising? Each pair of parenthesis is a group.

MK.
  • 33,605
  • 18
  • 74
  • 111