简单的正则表达式替换以保留原始字符串
我有这个:
Title = Regex.Replace(Title, s, "<span style=\"background:yellow\">" + s + "</span>", RegexOptions.IgnoreCase);
其中 s
是像 facebook
这样的词。如果标题是:
How to make a Facebook game
我想替换为:
How to make a <span style="background:yellow">Facebook</span> game
即使搜索词是“facebook”(注意大写)。基本上,我如何保留单词的原始大写?
另一个例子,搜索词FACEBOOK
,字符串Hello FaCeBoOk
被转换为Hello FaCeBoOk
I have this:
Title = Regex.Replace(Title, s, "<span style=\"background:yellow\">" + s + "</span>", RegexOptions.IgnoreCase);
Where s
is a word like facebook
. If the title is:
How to make a Facebook game
I would like to replaced to:
How to make a <span style="background:yellow">Facebook</span> game
Even if the search word is 'facebook' (note capitalisation). Basically, how do I retain the original capitalisation of the word?
Another example, search term FACEBOOK
, string Hello FaCeBoOk
is turned to Hello <span style="background:yellow">FaCeBoOk</span>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
$&
替换 来实现:You can use the
$&
substitution for that:您可以简单地包含与单词“facebook”匹配的捕获组,并将该捕获组作为替换字符串的一部分包含在内。这最终会将其包含在最终结果中,与输入中显示的完全相同。
查看实际操作。
You can simply include a capture group that matches the word "facebook", and include that capture group as part of the replacement string. This will end up including it in the end result exactly as it appeared in the input.
See it in action.
唯一重要的是
$+
。它包含最后获取的文本。这甚至适用于“如何制作 Facebook 游戏,你喜欢 Facebook 吗?”第一个 Facebook 将保留大写,第二个 Facebook 将保留小写。我要补充的是,如果您只想查找整个单词,那么您可以:
这将仅查找单词边界上的字符串。
The only important thing is the
$+
. It contains the last acquired text. This will work even for "How to make a Facebook game, do you like facebook?" The first Facebook will be left upper-case, the second one will be left lower-case.I'll add that if you want to look only for whole words, then you can make:
This will look only for strings that are on word boundary.