简体   繁体   中英

Regex replace whole word

I have this string:

Element 60:80 Node 1 2 3 Elm 55 Element 60 mpc 1:999 Elem 123

I want to replace all "Elm" "E" and "Elem" in my string to "Element". I don't want to replace "Node" to "NodElement" so I need to use word boundaries to match only whole words.

For that I'm using this regex:

Regex regexElements = new Regex("\b(E|Elm|Elem)\b", RegexOptions.IgnoreCase);

foreach(Match m in regexElements.Matches(str))
{
     MessageBox.Show("Match: " + m.Value");
}

str = regexElements.Replace(str, "Element"); //str is my string

But I don't see any replacement nor a MessageBox is being shown. The funny thing is that I can still target the desired words using Notepad++ search. What is happening here? Thanks

You need to raw your regex. \\b alone will not mean a word boundary (I'm not entirely sure what it means, but it's not a literal b , so it might be something like backspace). So either you use \\\\b or you use @ like in my comment, so that the final code becomes:

Regex regexElements = new Regex(@"\b(E|Elm|Elem)\b", RegexOptions.IgnoreCase);

foreach(Match m in regexElements.Matches(str))
{
     MessageBox.Show("Match: " + m.Value);
}

str = regexElements.Replace(str, "Element"); //str is my string

Or

Regex regexElements = new Regex("\\b(E|Elm|Elem)\\b", RegexOptions.IgnoreCase);

foreach(Match m in regexElements.Matches(str))
{
     MessageBox.Show("Match: " + m.Value);
}

str = regexElements.Replace(str, "Element"); //str is my string

I also propose this regex which is slightly more optimised:

@"\bE(le?m)?\b"

There's no need to use regex for that :

String yourString = "Element 60:80 Node 1 2 3 Elm 55 Element 60 mpc 1:999 Elem 123" ; 

yourString = yourString.Replace("Elem", "Element").Replace("E ", "Element ").Replace("Elm", "Element"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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