【问题标题】:Replacing only full words in a string with Regex仅用正则表达式替换字符串中的完整单词
【发布时间】:2010-03-03 14:12:48
【问题描述】:

我只想用 regex 替换句子中第一次出现的单词。

我只想替换完整的单词,因此排除部分匹配项。

例如,在句子“The quick brown foxy fox jumps over the lazy dog”中,我想将fox替换为cat

我能达到的结果是:“敏捷的棕猫狐狸跳过了懒惰的狗”。而不是foxy cat

我使用Regex.Replace方法如下:

var reg = new Regex(currentKeyword, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);

reg.Replace(input, replace, 1, 0);

【问题讨论】:

    标签: c# regex


    【解决方案1】:
    var reg = new Regex(@"\b" + currentKeyword + @"\b", ...);
    

    \b 表示word boundary

    【讨论】:

    • 感谢您的回答。我将 wRAR 标记为正确答案,因为他是第一个发布的,但您的解释是最好的。
    【解决方案2】:

    使用正确的正则表达式,例如@"\bcat\b"

    【讨论】:

      猜你喜欢
      • 2016-03-07
      • 2017-08-28
      • 2020-01-06
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 2023-03-13
      • 1970-01-01
      • 2017-06-23
      相关资源
      最近更新 更多