需要从下面提到的字符串中获取三个字符串,需要C#和 ASP.NET 中可能的解决方案:
"componentStatusId==2|3,screeningOwnerId>0"
我需要在 C# 中使用正则表达式获取"2"、"3"和"0">
如果你想要的只是字符串中的数字,那么你可以在这段代码中使用正则表达式:
string re = "(?:\b(\d+)\b[^\d]*)+";
Regex regex = new Regex(re);
string input = "componentStatusId==2|3,screeningOwnerId>0";
MatchCollection matches = regex.Matches(input);
for (int ii = 0; ii < matches.Count; ii++)
{
Console.WriteLine("Match[{0}] // of 0..{1}:", ii, matches.Count - 1);
DisplayMatchResults(matches[ii]);
}
函数DisplayMatchResults
取自此堆栈溢出答案。
上面的控制台输出是:
Match[0] // of 0..0:
Match has 1 captures
Group 0 has 1 captures '2|3,screeningOwnerId>0'
Capture 0 '2|3,screeningOwnerId>0'
Group 1 has 3 captures '0'
Capture 0 '2'
Capture 1 '3'
Capture 2 '0'
match.Groups[0].Value == "2|3,screeningOwnerId>0"
match.Groups[1].Value == "0"
match.Groups[0].Captures[0].Value == "2|3,screeningOwnerId>0"
match.Groups[1].Captures[0].Value == "2"
match.Groups[1].Captures[1].Value == "3"
match.Groups[1].Captures[2].Value == "0"
因此,可以在match.Groups[1].Captures[...]
中看到这些数字。
另一种可能性是使用模式为"非数字"的Regex.Split
。以下代码的结果需要后处理以删除空字符串。请注意,Regex.Split
没有字符串Split
方法的StringSplitOptions.RemoveEmptyEntries
。
string input = "componentStatusId==2|3,screeningOwnerId>0";
string[] numbers = Regex.Split(input, "[^\d]+");
for (int ii = 0; ii < numbers.Length; ii++)
{
Console.WriteLine("{0}: '{1}'", ii, numbers[ii]);
}
由此产生的输出是:
0: ''
1: '2'
2: '34'
3: '0'
使用以下正则表达式并从组 1、2 和 3 中捕获您的值。
componentStatusId==(d+)|(d+),screeningOwnerId>(d+)
演示
要使用任何字符串泛化componentStatusId
和screeningOwnerId
,您可以在正则表达式中使用w+
并使其更通用。
w+==(d+)|(d+),w+>(d+)
更新的演示