簡體   English   中英

使用正則表達式在字符串中查找確切的字符

[英]Find exact characters in string using regex

我有下面的字符串

M10 end 
start M11
M1
M1 start
M n1
end M1

我想要實現的是使用正則表達式獲得只有“ M1 ”的結果。

這是我目前的代碼

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

輸出如下所示,缺少字符串“M1 start”

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

這應該為你做。參見demo.Here \\b是單詞邊界,它只匹配M1而不是M10

\\ b在字邊界處斷言位置(^ \\ w | \\ w $ | \\ W \\ w | \\ w \\ W)

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

好吧,如果你不想過度使用Regex,你可以使用

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

使用StringReader分割每一行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM