[英]Trying to get multiple RegEx matches with named groups in C#
我有一個像這樣的字符串:
如果您的使用量介於1,000 kWh和1,500 kWh之間,則每個計費周期將獲得$ 80的住宅使用抵免額。 如果您的使用量介於1,501 kWh和2,000 kWh之間,則每個結算周期將獲得$ 40的住宅使用抵免額。
您會看到兩個句子的格式重復。 我使用如下命名組創建了一個正則表達式:
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;
}
這對於我當前的情況非常有效,因為在我的大多數情況下,我都不會像上面的示例那樣重復該過程。 但是,當我確實有一個斷點並查看它是否同時捕獲了兩個匹配項時,它只會在“ match”對象上獲得對象的第一個(即本示例中的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();
}
在Regex.Match方法(字符串)中查看示例,以查看如何在字符串中多次匹配。 我認為您想要的是以下內容:
while (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);
}
match = match.NextMatch();
}
return results.Count > 0 ? results.ToArray() : null;
這將用while
語句替換if
語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.