使用正则表达式 regex.match 并配合模式 \d+ 即可提取字符串中第一次出现的连续数字。该方法会返回匹配到的第一个子串,若未找到则返回空值。调用时只需传入目标字符串,无需额外配置选项。

如何区分纯数字与带单位的数值提取?
当需要提取的数字可能包含小数点或负号时,标准 \d+ 仅匹配整数部分。若需支持浮点数或负数,应使用更复杂的正则模式如 -?\d+(\.\d+)?。这种模式下,Match 依然只返回第一次出现的最长匹配项,确保结果符合预期格式。

如果字符串中没有数字,Match 的返回值是什么?
当输入字符串不包含任何数字字符时,Regex.Match 返回的 Match 对象的 Success 属性为 false,且 Value 为空字符串。此时直接访问 Value 不会报错,但结果为空。开发者应在代码中检查 Success 属性以避免后续逻辑错误。
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string input1 = "Order123Done";
Match match1 = Regex.Match(input1, @"\d+");
Console.WriteLine(match1.Success ? match1.Value : "No match");
string input2 = "NoDigitsHere";
Match match2 = Regex.Match(input2, @"\d+");
Console.WriteLine(match2.Success ? match2.Value : "No match");
string input3 = "Price-45.99USD";
Match match3 = Regex.Match(input3, @"-?\d+(\.\d+)?");
Console.WriteLine(match3.Success ? match3.Value : "No match");
}
}











