如下:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "abc 123 def 456";
//获取字符串中所有的数字
MatchCollection matches = Regex.Matches(input, @"\d+");
foreach (Match match in matches)
{
Console.WriteLine(match.Value);
}
//获取字符串中的最后一个数字
if (matches.Count > 0)
{
Match lastMatch = matches[matches.Count - 1];
Console.WriteLine("Last integer found: " + lastMatch.Value);
}
else
{
Console.WriteLine("No integer found in the input string.");
}
//获取字符串中的第一个数字
Match match = Regex.Match(input, @"\d+");
if (match.Success)
{
Console.WriteLine("First number found: " + match.Value);
}
else
{
Console.WriteLine("No numbers found in the input string.");
}
}
}