Regex matches missing one match?

前端 未结 2 765
野的像风
野的像风 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: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()
        .Select(m => m.Groups[1].Value)
        .ToList();
    

    See the regex demo

提交回复
热议问题