简体   繁体   English

使用正则表达式在字符串中查找确切的字符

[英]Find exact characters in string using regex

I have strings like below 我有下面的字符串

M10 end 
start M11
M1
M1 start
M n1
end M1

What I am trying to achieve is get the result having only " M1 " using regex. 我想要实现的是使用正则表达式获得只有“ M1 ”的结果。

This is my current code 这是我目前的代码

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

The output looks like below which is missing string "M1 start" 输出如下所示,缺少字符串“M1 start”

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

This should do it for you.See demo.Here \\b is word boundary which will match only M1 and not M10 . 这应该为你做。参见demo.Here \\b是单词边界,它只匹配M1而不是M10

\\b assert position at a word boundary (^\\w|\\w$|\\W\\w|\\w\\W) \\ b在字边界处断言位置(^ \\ w | \\ w $ | \\ W \\ w | \\ w \\ W)

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

Well, if you want not to overuse Regex, you can use 好吧,如果你不想过度使用Regex,你可以使用

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

using a StringReader to split each line. 使用StringReader分割每一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM