字符串替换整个单词而不是子字符串

编程入门 行业动态 更新时间:2024-10-27 22:33:56
本文介绍了字符串替换整个单词而不是子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我要替换整个单词,而不是部分匹配. 例如:我想替换文件中的".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#(代码)文件中执行此操作,而不是在运行时代码中进行操作,则在中进行操作这样的设施. 您可以使用一些技巧, 首先将 key.addListener 替换为一些字符串,并以您的名字 现在,将 .addListener 替换为您想要的任何内容. 然后用 key.addListener 替换您的名字 祝您编码愉快! :) if you are asking for doing it in C# (code)file not for run-time code then in 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

更多推荐

字符串替换整个单词而不是子字符串

本文发布于:2023-06-02 12:40:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/447338.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   单词   而不是

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!