PCRE regular expression overlapping matches

后端 未结 1 387
野趣味
野趣味 2020-12-01 22:14

i have the following string

001110000100001100001

and this expression

/[1]....[1]/g

this makes two matc

相关标签:
1条回答
  • 2020-12-01 22:58

    A common trick is to use capturing technique inside an unanchored positive lookahead. Use this regex with preg_match_all:

    (?=(1....1))
    

    See regex demo

    The values are in $matches[1]:

    $re = "/(?=(1....1))/"; 
    $str = "001110000100001100001"; 
    preg_match_all($re, $str, $matches);
    print_r($matches[1]);
    

    See lookahead reference:

    Lookaround actually matches characters, but then gives up the match, returning only the result: match or no match. That is why they are called "assertions". They do not consume characters in the string, but only assert whether a match is possible or not.

    If you want to store the match of the regex inside a lookahead, you have to put capturing parentheses around the regex inside the lookahead, like this: (?=(regex)).

    0 讨论(0)
提交回复
热议问题