Sturm
Sturm

Reputation: 4125

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

Upvotes: 3

Views: 1583

Answers (2)

Jerry
Jerry

Reputation: 71538

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"

Upvotes: 4

Perfect28
Perfect28

Reputation: 11317

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"); 

Upvotes: 0

Related Questions