![](/img/trans.png)
[英]Validate a string of certain characters and numeric of exact length using Regex
[英]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)
好吧,如果你不想過度使用Regex,你可以使用
target="M1";
if( underTest.IndexOf(target) == 0 && underTest.Lenght == target.Lenght)
{
....
}
使用StringReader
分割每一行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.