如何用C#正则表达式提取指定字符串中的数字2、3、0?
C#正则表达式提取指定字符串中的数字值
针对字符串componentStatusId==2|3,screeningOwnerId>0,可以用以下两种正则思路提取目标数字:
方案1:提取所有连续数字序列
这种方式简单直接,能匹配字符串中所有的数字片段,刚好符合需求提取2、3、0:
正则表达式:\d+
对应的C#代码示例:
using System; using System.Text.RegularExpressions; public class Program { public static void Main() { string input = "componentStatusId==2|3,screeningOwnerId>0"; // 匹配所有连续数字 MatchCollection matches = Regex.Matches(input, @"\d+"); foreach (Match match in matches) { Console.WriteLine(match.Value); // 依次输出2、3、0 } } }
方案2:精准匹配运算符后的数字
如果需要只提取==或>符号后的数字(避免误匹配其他可能存在的数字),可以使用带正向预查的正则:
正则表达式:(?<==>|>)\d+
对应的C#代码示例:
using System; using System.Text.RegularExpressions; public class Program { public static void Main() { string input = "componentStatusId==2|3,screeningOwnerId>0"; // 匹配==或>之后的数字 MatchCollection matches = Regex.Matches(input, @"(?<==>|>)\d+"); foreach (Match match in matches) { Console.WriteLine(match.Value); // 依次输出2、3、0 } } }
代码说明
Regex.Matches方法会返回输入字符串中所有匹配正则表达式的结果集合- 遍历
MatchCollection,通过match.Value获取每个匹配到的数字字符串 - 两种方案都能满足需求,方案1更通用,方案2更精准,可根据实际场景选择
内容的提问来源于stack exchange,提问作者user15019772
相关产品推荐
相关产品推荐

