您正在使用的正则表达式是正确的 . 要解决您的问题,您可以使用 capture groups ,如下所示:
string str = “The quick brown fox jumps over the lazy dog”;
Regex r = new Regex(@”s+([^s]+)”);
Match m = r.Match(str);
System.Console.WriteLine(m.Groups[1]);
这将产生 quick ,没有尾随空格 .
或者,您也可以在结果上使用 trim() 方法 .
另外,根据您的附注,您可以通过组合C#和正则表达式来匹配给定句子的 nth 单词,这样的事情应该做您需要的:
string str = “The quick brown fox jumps over the lazy dog”;
Regex r = new Regex(@”(^|s)+([^s]+)”);
MatchCollection mc = r.Matches(str);
for (int i = 0; i < mc.Count; i++)
{
System.Console.WriteLine(mc[i].Groups[2]);
}
产量:
The
quick
brown
fox
jumps
over
the
lazy
dog
我不得不对正则表达式进行修改以考虑第一个字 . 这允许正则表达式选择前面有空格的单词,或者字符串的开头 .
根据您的评论,请查看this链接 .