简体   繁体   English

正则表达式取代整个单词

[英]Regex replace whole word

I have this string: 我有这个字符串:

Element 60:80 Node 1 2 3 Elm 55 Element 60 mpc 1:999 Elem 123 元素60:80节点1 2 3榆木55元素60 mpc 1:999 Elem 123

I want to replace all "Elm" "E" and "Elem" in my string to "Element". 我想将我的字符串中的所有“Elm”“E”和“Elem”替换为“Element”。 I don't want to replace "Node" to "NodElement" so I need to use word boundaries to match only whole words. 我不想将“Node”替换为“NodElement”,所以我需要使用单词边界来匹配整个单词。

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. 但我没有看到任何替换,也没有显示MessageBox。 The funny thing is that I can still target the desired words using Notepad++ search. 有趣的是,我仍然可以使用Notepad ++搜索来定位所需的单词。 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). \\b单独不会意味着单词边界(我不完全确定它是什么意思,但它不是文字b ,所以它可能类似于退格)。 So either you use \\\\b or you use @ like in my comment, so that the final code becomes: 所以你要么使用\\\\b要么在我的评论中使用@ like,这样最终的代码就变成:

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

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

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