Is there a regex flavor that allows me to count the number of repetitions matched by the * and + operators?

后端 未结 3 1778
情深已故
情深已故 2020-11-28 16:36

Is there a regex flavor that allows me to count the number of repetitions matched by the * and + operators? I\'d specifically like to know if it\'s

3条回答
  •  忘掉有多难
    2020-11-28 17:05

    You can use parentheses in the expression to create a group and then use the + or * operator on the group. The Captures property of the Group can be used to determine how many times it was matched. The following example counts the number of consecutive lower-case letters at the start of a string:

    var regex = new Regex(@"^([a-z])+");
    var match = regex.Match("abc def");
    
    if (match.Success)
    {
        Console.WriteLine(match.Groups[1].Captures.Count);
    }
    

提交回复
热议问题