【问题标题】:Regex Replace all found occurrences if the word not matches with the given prefix正则表达式 如果单词与给定前缀不匹配,则替换所有找到的匹配项
【发布时间】:2012-11-14 03:36:33
【问题描述】:

如何在不匹配给定文本前缀的情况下替换文本值??

例如:

test hello world... I know hello world, this seems hello world..

那么我们的替换值为“HI”

文本将是..

test hello world... I know HI, this seems HI..

【问题讨论】:

  • 你的意思是“test”这个词不在“hello world”之前?
  • 所以你的意思是你想用 hi 替换字符串中的 hello world
  • 如果找到hello world之前的word test,则不会进行替换过程。但如果没有找到,hello world 将被替换为 HI

标签: c# regex regex-negation regex-lookarounds


【解决方案1】:
(?<!test\s)\bhello world\b

这假设您对直接进行的测试感兴趣。

【讨论】:

  • 谢谢。这以某种方式帮助我:)
【解决方案2】:

为了有点聪明并避免使用正则表达式,你可能会做这样的事情

string v = s.Replace("hello world", "HI"); //replace hello world in all occurrences with HI 

string newstring  = v.Replace("test HI", "hello world"); //place hello world where hi is after test 

【讨论】:

    猜你喜欢
    • 2016-11-04
    • 1970-01-01
    • 2019-07-27
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多