要保留C#中Regex.Split中匹配的模式,可以使用正则表达式的捕获组来实现。下面是一个示例代码:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string input = "Hello,world!123456";
string pattern = @"(\d+)"; // 匹配数字
string[] result = Regex.Split(input, pattern);
foreach (string s in result)
{
Console.WriteLine(s);
}
}
}
在上面的示例中,我们使用正则表达式 (\d+)
来匹配数字。该正则表达式中的 (\d+)
是一个捕获组,用于匹配一个或多个数字。Regex.Split方法会根据该捕获组的匹配结果将字符串分割成多个子字符串。
运行上述代码,输出结果如下:
Hello,world!
123456
可以看到,通过使用捕获组,我们成功将匹配的模式保留下来,并将匹配的数字作为独立的子字符串输出。