You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 21:50:24