【发布时间】:2012-02-08 12:49:23
【问题描述】:
我正在寻找一个正则表达式来拆分其中的文本。 我已经测试过了
Regex.Split(text, @"\s+")
但这给了我例如
this (is a) text. and
this
(is
a)
text
and
但我寻找一个解决方案,它只给我单词 - 没有 (, ), 。等等 它还应该像
这样拆分文本end.begin
就两个字。
【问题讨论】:
我正在寻找一个正则表达式来拆分其中的文本。 我已经测试过了
Regex.Split(text, @"\s+")
但这给了我例如
this (is a) text. and
this
(is
a)
text
and
但我寻找一个解决方案,它只给我单词 - 没有 (, ), 。等等 它还应该像
这样拆分文本end.begin
就两个字。
【问题讨论】:
试试这个:
Regex.Split(text, @"\W+")
\W 与 \w 对应,表示字母数字。
【讨论】:
你可能最好匹配单词而不是分裂。
如果您使用Split(将\W 用作Regexident suggested),那么您可能会在开头和结尾处获得一个额外的字符串。例如,输入字符串 (a b) 将为您提供 四个 输出:""、"a"、"b" 和另一个 "",因为您使用的是 ( 和) 作为分隔符。
您可能想要做的只是匹配单词。你可以这样做:
Regex.Matches(text, "\\w+").Cast<Match>().Select(match => match.Value)
然后你将只得到单词,并且在开头和结尾没有多余的空字符串。
【讨论】:
Regex.Matches返回的MatchCollection只包含Match的实例,.Cast<Match>会比.OfType<Match>更合适,因为不需要基于类型的过滤。
你可以这样做:
var text = "this (is a) text. and";
// to replace unwanted characters with space
text = System.Text.RegularExpressions.Regex.Replace(text, "[(),.]", " ");
// to split the text with SPACE delimiter
var splitted = text.Split(null as char[], StringSplitOptions.RemoveEmptyEntries);
foreach (var token in splitted)
{
Console.WriteLine(token);
}
看到这个Demo
【讨论】: