Why doesn't this regex capture group repeat for each match?

前端 未结 1 1384
闹比i
闹比i 2021-01-21 00:32

I\'m testing this on regex101.com

Regex: ^\\+([0-9A-Za-z-]+)(?:\\.([0-9A-Za-z-]+))*$

Test string: +beta-bar.baz-bz.fd.zz

The st

相关标签:
1条回答
  • 2021-01-21 01:09

    The reason why that happens is because when using a quantifier on a capture group and it is captured n times, only the last captured text gets stored in the buffer and returned at the end.

    Instead of matching those parts, you can preg_split the string you have with a simple regex [+.]:

    $str = "+beta-bar.baz-bz.fd.zz";
    $a = preg_split('/[+.]/', $str, -1, PREG_SPLIT_NO_EMPTY);
    

    See IDEONE demo

    Result:

    Array
    (
        [0] => beta-bar
        [1] => baz-bz
        [2] => fd
        [3] => zz
    )
    
    0 讨论(0)
提交回复
热议问题