Why does this regex capture give 2 matches?
I don't know why there are two matches found outside of the input using this regex when I was only expecting 1 match.
preg_match(/_(\d(-\d){0,3})\./,$str,$matches);
in this string format name_A-B-C-D.ext
.
I would expect to get one match:
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:
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 want to write A
before D
if it is preceded by a hyphen. This code can be used and I can just ignore the second match, but I would like to know why its there. I can only assume that it has something to do with my two capture groups. Where is my mistake?
Yes, you get two snapshots because there are two capture groups in your regex.
To avoid unwanted capture, you can use a non-capture group (?:...)
:
/_(\d(?:-\d){0,3})\./
I can only assume that it has something to do with my two capture groups.
Your guess is correct
Where is my mistake?
No errors, everything behaves as expected.
You have groups in your RE, so you get 2 matches. What's amazing? Each pair of brackets represents a group.