2015-04-16 11 views
4

我有一個像下面使用正則表達式查找字符串的字符準確

M10 end 
start M11 
M1 
M1 start 
M n1 
end M1 

我想實現的就是隻有「M1」使用正則表達式的結果字符串。

這是我當前的代碼

Regex r = new Regex("^M1$|M1$"); 

輸出類似於下面一個缺少字符串 「M1開始」

M1 
end M1 
+0

你想讓它匹配'start M1 end'嗎? – ClickRick

回答

5
Regex r = new Regex("^.*\\bM1\\b.*$"); 

這應該u太強勢了demo.Here做\b是僅與M1匹配的字邊界,而不是M10

\在單詞邊界B斷言位置(^ \ W | \ W $ | \ W \ W | \ W \ W)

https://regex101.com/r/sJ9gM7/113

1

好吧,如果你想不要過度使用正則表達式,您可以使用

target="M1"; 
if(underTest.IndexOf(target) == 0 && underTest.Lenght == target.Lenght) 
{ 
.... 
} 

使用StringReader分割每一行。

相關問題