2010-11-23 129 views
5

我希望能夠匹配整個字符串(因此字邊界)與模式「ABC」(「ABC」僅用於方便,我不想檢查與固定字符串的相等性),所以換行符對我很重要。但是,在字符串末尾放置一個單獨的「\ n」會被忽略。我的模式有什麼問題嗎?如何匹配一個字符串,忽略結束換行符?

Regex r = new Regex(@"^ABC$"); 
string[] strings = 
{ 
    "ABC",//True 
    "ABC\n",//True: But, I want it to say false. 
    "ABC\n\n",//False 
    "\nABC",//False 
    "ABC\r",//False 
    "ABC\r\n",//False 
    "ABC\n\r"//False 
}; 
foreach(string s in strings) 
{ 
    Console.WriteLine(r.IsMatch(s)); 
} 

回答

4

嘗試此(未測試):

Regex r = new Regex(@"\AABC\z"); 

\A =錨字符串的開頭
\z =錨爲字符串的結尾
^ =錨爲線的開頭
$ =結束行錨

+0

謝謝。在你的答案後找到這個:http://msdn.microsoft.com/en-us/library/h5181w5w(v=VS.100).aspx – blizpasta 2010-11-23 03:02:52

相關問題