使用正则表达式 regex.match 并配合模式 [0-9]+ 可以截取字符串中第一段连续数字。调用该方法后,通过访问返回结果的 value 属性即可获取截取的数字子串。如果字符串中没有匹配的数字,match 的 success 属性将为 false,此时 value 为空字符串。

如何提取字符串中所有连续数字序列?
若需提取所有而非仅第一段连续数字,应使用 Regex.Matches 方法。该方法会返回一个 MatchCollection 集合,遍历该集合即可获取所有匹配到的数字片段。这种方式适用于需要从混合文本中提取多个独立数值段的场景。

using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "Item123Code456End";
// 截取第一段连续数字
Match firstMatch = Regex.Match(input, @"[0-9]+");
if (firstMatch.Success)
{
Console.WriteLine("First number: " + firstMatch.Value);
}
else
{
Console.WriteLine("No numbers found.");
}
// 提取所有连续数字
MatchCollection allMatches = Regex.Matches(input, @"[0-9]+");
foreach (Match match in allMatches)
{
Console.WriteLine("All numbers: " + match.Value);
}
}
}
对于输入 Item123Code456End,上述代码的预期输出为:
First number: 123
All numbers: 123
All numbers: 456
当字符串中包含负号时,如何正确截取带符号的数字?
默认的正则表达式 [0-9]+ 无法捕获负数中的减号。若需截取包含前导负号的连续数字(如 -42),应将模式修改为 -?[0-9]+。这会在匹配数字前可选地包含一个减号,从而正确处理负整数。
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "Price is -50 dollars";
// 截取带符号的连续数字
Match signedMatch = Regex.Match(input, @"-?[0-9]+");
if (signedMatch.Success)
{
Console.WriteLine("Signed number: " + signedMatch.Value);
}
}
}
对于输入 Price is -50 dollars,使用 -?[0-9]+ 模式将成功截取 -50,而使用原模式仅会截取 50。


















