Find exact characters in a string using regex

I have lines as below

M10 end 
start M11
M1
M1 start
M n1
end M1

What I'm trying to achieve is to get a result that has only " M1 " with regex.

This is my current code.

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

The result looks lower, where the line "Start M1" is missing

M1
end M1
+4
source share
2 answers
Regex r = new Regex("^.*\\bM1\\b.*$");

That should do it for you. See demo.Here \b- a word boundary that will only match M1, not M10.

\ b state the position on the word boundary (^ \ w \\ w $ \\ W \ w \\ w \ W)

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

+5
source

Well, if you do not want to abuse Regex, you can use

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

StringReader .

+1

All Articles