2012-02-08 47 views
0

我正在尋找一個正則表達式來分割文本中的文字。 我已經測試正在搜索正則表達式來分割文本中的文字

Regex.Split(text, @"\s+") 

但是這給了我,例如用於

this (is a) text. and 

this 
(is 
a) 
text 
and 

但我尋找一個解決方案,這給了我只有四個字 - 沒有(,)。等 還應該用兩個詞分裂樣

end.begin 

文本。

回答

0

你可能會更好過匹配的話而不是分裂。

如果您使用Split\WRegexident suggested),那麼您可以在開始和結束時獲得額外的字符串。例如,輸入字符串(a b)會給你輸出:"""a""b",另有"",因爲你使用的()分隔符。

你可能想要做的只是匹配單詞。你可以這樣做:

Regex.Matches(text, "\\w+").Cast<Match>().Select(match => match.Value) 

然後你會得到的只是單詞,並沒有額外的空字符串在開始和結束。

+0

由於'Regex.Matches'返回的'MatchCollection'只包含'Match'的實例,'.Cast '比'.OfType '更合適,因爲不需要基於類型的過濾。 – spender 2012-02-08 13:33:36

+0

@spender,很好的電話。改變。 – 2012-02-08 13:43:34

5

嘗試這種情況:

Regex.Split(text, @"\W+") 

\W是對應於\w,這意味着字母數字。

0

你可以這樣做:

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