正则表达式匹配整个单词 [英] Regex to match whole word

查看:109
本文介绍了正则表达式匹配整个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 stackoverflow 上看到了很多关于使用正则表达式进行全字匹配的例子.我有以下情况,我想用 www.xyz.com 替换 www.abc.com .

I saw many examples on stackoverflow regarding whole word match using Regex. I have the following situation where I want to replace www.abc.com with www.xyz.com .

string RetVal = "I am going to visit www.abc.com";
string TextToFind = @"\bwww.abc.com\b";
string TextToReplace = "www.xyz.com";
bool IgnoreCase = true;
RegexOptions regOpt = RegexOptions.None;
if (IgnoreCase)
    regOpt = RegexOptions.IgnoreCase;
RetVal = Regex.Replace(RetVal, TextToFind,TextToReplace, regOpt);

上面工作正常.但是当我改变时

above is working fine.But when I change

RetVal = "I am going to visit www.abc.com/xyz.html";

它仍在将 www.abc.com 替换为 www.xyz.com,我不想替换它.

It is still replacing www.abc.com to www.xyz.com and I do not want to replace that.

推荐答案

您似乎只想在被替换的字符串周围只有空格或行首/行尾.

You seem to want to have only white spaces or begin/end of line around your replaced string.

使用诸如(^|\s)string 之类的东西来替换(\s|$).不确定您使用的是什么语言,您可能需要稍微调整此字符串.

Use somehting like (^|\s)string to replace(\s|$). Not sure what language you are using you may need to tune this string a little bit.

这篇关于正则表达式匹配整个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆