使用正则表达式在字符串中查找确切的字符
我有下面的字符串
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)
好吧,如果你不想过度使用正则表达式,你可以使用
target="M1"; if( underTest.IndexOf(target) == 0 && underTest.Lenght == target.Lenght) { .... }
使用StringReader
分割每一行。