如何使用正则表达式保留分隔符?
我尝试了以下
string str = "user1;user2;user3;user4";
Regex regex = new Regex(@"\w;");
string[] splites = regex.Split(str);
foreach (string match in splites)
{
Console.WriteLine("'{0}'", match);
Console.WriteLine(Environment.NewLine);
}
输出:
user1
user2
user3
user4
我想如下但不要:
输出:
user1;
user2;
user3;
user4
答案 0 :(得分:1)
Regex.Matches
似乎更合适:
string str = "user1;user2;user3;user4";
Regex re = new Regex(@"\w+;?");
foreach (var match in re.Matches(str)) {
Console.WriteLine(match);
}
或者你可以使用lookbehind断言:
string str = "user1;user2;user3;user4";
Regex re = new Regex(@"(?<=;)");
foreach (var match in re.Split(str)) {
Console.WriteLine(match);
}
答案 1 :(得分:0)
你可以尝试这样的事情
string str = "user1;user2;user3;user4";
MatchCollection matchs= Regex.Matches(str, @"[\w]+;?");
foreach (Match m in matchs)
{
Console.WriteLine(m.Value);
}