Regex matches missing one match?

前端 未结 2 760
野的像风
野的像风 2020-11-28 00:02

I have the regex 1(0*)1 and the test string 1000010001

I want to have 2 matches, but I find that only 1 gets found :

var re         


        
相关标签:
2条回答
  • 2020-11-28 00:16

    You are already selecting the 1 in front of the second zero by the first match.

    100001 0001
    ^^^^^^
    

    This is the first match. The rest is just 0001 which does not match your regex.


    You can circumvent this behavior if you are using lookaheads/lookbehinds:

    (?<=1)(0*)(?=1)
    

    Live example


    Because you cannot use lookbehinds in JavaScript, it is enough to only use one lookahead, to prevent the overlapping:

    1(0*)(?=1)
    

    Live example


    And a hint for your regex101 example: You did not add the global flag, which prevents more than one selection.

    0 讨论(0)
  • 2020-11-28 00:31

    You need to match overlapping strings.

    It means you should wrap your pattern with a capturing group (( + your pattern + )) and put this consuming pattern into a positive lookahead, then match all occurrences and grab Group 1 value:

    (?=(YOUR_REGEX_HERE))
    

    Use

    var regex = new Regex("(?=(10*1))");
    var values = regex.Matches(intBinaryString)
        .Cast<Match>()
        .Select(m => m.Groups[1].Value)
        .ToList();
    

    See the regex demo

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