Skip to main content
 首页 » 编程设计

c#之尝试在 C# 中获取与命名组的多个正则表达式匹配

2024年01月31日27lyhabc

我有这样一个字符串:

A Residential Usage Credit of $80 will be applied for each billing cycle in which YOUR USAGE falls between 1,000 kWh and 1,500 kWh. A Residential Usage Credit of $40 will be applied for each billing cycle in which YOUR USAGE falls between 1,501 kWh and 2,000 kWh.

你可以看到这两个句子有重复的格式。我使用这样的命名组创建了一个正则表达式:

A Residential Usage (?<costType>[\w\s]+) of \p{Sc}*(?<cost>\s?\d+[., ]?\d*) will be applied for each billing cycle in which YOUR USAGE falls between (?<firstUsage>[0-9, ]+) kWh and (?<secondUsage>[0-9, ]+) kWh 

我有很多这样的字符串组合要用命名组进行正则表达式捕获,我使用这个函数来捕获它们:

  public static string[] ValidatePattern(string pattern, string input, List<string> groupNames) 
    { 
        Regex regex = new Regex(pattern); 
        var match = regex.Match(input); 
 
        List<string> results = new List<string>(); 
        if (match.Success) 
        { 
            //results.Add(input); 
            foreach (var name in groupNames) 
            { 
                if (match.Groups[name].Captures.Count > 0) results.Add(match.Groups[name].Value); 
                else results.Add(String.Empty); 
            } 
            return results.ToArray(); 
        } 
        return null; 
    } 

这对我目前的情况很有效,因为对于我的大多数场景,我没有像上面的例子那样重复。但是,当我确实有一个断点并查看它是否捕获了两个匹配项时,它只会在“匹配”对象上获得对象上的第一个(即本例中的 1,000 到 1500)。

我的问题是,如何获得 Regex 对象的第二个匹配项?我可以从那里重构,但我不知道如何获取数据。

请您参考如下方法:

您需要遍历字符串的所有匹配项。 Regex.Match 将只返回第一个匹配项。

public static string[] ValidatePattern(string pattern, string input, List<string> groupNames) 
{ 
    Regex regex = new Regex(pattern); 
    var matches = regex.Matches(input); 
 
    List<string> results = new List<string>(); 
    foreach (Match match in matches) { 
        foreach (var name in groupNames) 
        { 
            var group = match.Groups[name]; 
            results.Add(group.Success ? group.Value : string.Empty); 
        } 
    } 
    return results.ToArray(); 
}