字符串替换整个单词而不是子字符串 [英] String replace whole word and not substring

查看:126
本文介绍了字符串替换整个单词而不是子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要替换整个单词,而不是部分匹配.
例如:我想替换文件中的".addListener"字符串.但是我不想替换包含"key.addListener"的字符串.
有没有办法做这样的替换?

I want to replace the whole word and not partial matches.
for eg:I want to replace ".addListener" string in a file.But I don''t want to replace string that contains "key.addListener".
Is there a way to do such replacements?

推荐答案

如果您要求在C#(代码)文件中执行此操作,而不是在运行时代码中进行操作,则在.net中进行操作这样的设施.
您可以使用一些技巧,
首先将 key.addListener 替换为一些字符串,并以您的名字
现在,将 .addListener 替换为您想要的任何内容.
然后用 key.addListener
替换您的名字
祝您编码愉快!
:)
if you are asking for doing it in C# (code)file not for run-time code then in .net not such facility.
you can use some trick,
first replace key.addListener with some string suppose with your name
now, replace .addListener with whatever you want.
and then re-replace your name with key.addListener

Happy Coding!
:)


您可能想使用Regex,下面的示例代码可能会帮助

You may want to use Regex , a sample code below may help

string inputString = "key.addListener .addListener"; 
string patternToReplace= @"\B.addListener\b"; 
string result = Regex.Replace(inputString , patternToReplace, ""); 


现在结果将包含只删除整个单词.addListener的字符串

注意:由于您要删除的字词开头是.正则表达式的第一部分是/B 如果它是正常单词(如addListener而不带).然后在正则表达式模式的开头使用/b .

希望有帮助.
-Milind
如果有帮助,请标记为答案/赞扬


Now result will contain string for which only whole word .addListener is removed

Note: Since the start of hte word you are looking to remove is . the first part of the regex is /B If it is normal word like addListener without the . then use /b at the start of the regex pattern.

Hope that helps.
-Milind
Do mark as answer/upvote if it helps


这篇关于字符串替换整个单词而不是子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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