2016-05-31 28 views
-2

我有如下文字如何將括號內的文本與c#中的正則表達式匹配?

has helped discover and mentor such </br> 
New York Times bestselling authors as Brandon Sanderson </br> 
(Mistborn), James Dashner (The Maze Runner), and Stephenie 

我以第一行的最後3個字和最後一個行的第3個字的使用正則表達式來查找文本之間。我在c#代碼中使用以下正則表達式。

string matchedText = ""; 
string RegexPattren = preLine + "[\\w\\W\\S\\s\\s\\D':;\"<>,.?]*" + postLine; 
matchedText = Regex.Match(stBuilder.ToString(), RegexPattren).Value; 
matchedText = preLine.Equals("") ? matchedText : matchedText.Replace(preLine, ""); 
matchedText = postLine.Equals("") ? matchedText : matchedText.Replace(postLine, ""); 
string[] MatchedLines = Regex.Split(matchedText, "</br>").Where(x => !string.IsNullOrEmpty(x.Trim())).ToArray(); 



string RegexPattren = preLine + "[\\w\\W\\S\\s\\s\\D':;\"<>,.?]*" + postLine; 

具有followig值

and mentor such [\w\W\S\s\s\D':;"<>,.?]* James Dashner 

以上代碼工作正常和匹配結果是,當用括號中的詞被找到一樣下面發生

and mentor such </br>New York Times bestselling authors as Brandon Sanderson </br>(Mistborn), James Dashner 

問題,正則表達式不匹配任何文字。

and mentor such [\w\W\S\s\s\D':;"<>,.?]* (Mistborn), James Dashner 

如何匹配c#中的正則表達式模式之前或之後有括號內的文本行嗎?

回答

1

你必須逃離像

and mentor such [\w\W\S\s':;"<>,.?]*\(Mistborn\), James Dashner 

括號這將使它符合字面()

並注意你的正則表達式在文本中不存在的(Mistborn)之前有一個空格。它之前有一個換行符。我刪除了空格,但是您也可以將其更改爲\s,該空格和換行符都匹配。

最後,\D與非數值匹配,已由\W處理,因爲數字匹配\w。實際上,班級中的幾個角色可以被刪除。如果設置了RegexOptions.Singleline你很可能會確定與

and mentor such .*\(Mistborn\), James Dashner 

Check it out here at regex101

PS。有一種.NET方法來逃避正則表達式,Regex.Escape,但是這使實際的正則表達式複雜化。

相關問題