You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Groovy中如何实现字符串的精确匹配单词替换?

解决Groovy中精确匹配单词替换的问题

你的问题出在两个核心点:

  • 普通的replace方法是字面量全匹配替换,会把所有包含目标子串的内容都替换,所以Richardson里的Richards子串也被替换成了Praveen,最终出现Praveenon的错误结果。
  • 直接用"\bRichards\b"时,Groovy里的\b是退格控制字符,不是正则表达式中的单词边界,因此无法实现精确单词匹配。

正确的解决方案

使用Groovy的replaceAll方法结合正则表达式的单词边界\b,同时适配Groovy的字符串转义规则,有两种简洁写法:

写法一:双反斜杠转义单词边界

在普通字符串中,\需要转义为\\,因此正则表达式需写成"\\bRichards\\b":

def str = "My Name is Richards and Richardson"
log.info(str)
str = str.replaceAll("\\bRichards\\b", "Praveen")
log.info("After" + str)

写法二:使用Groovy斜杠字符串(推荐)

Groovy的斜杠字符串/.../不需要转义反斜杠,写法更直观:

def str = "My Name is Richards and Richardson"
log.info(str)
str = str.replaceAll(/\bRichards\b/, "Praveen")
log.info("After" + str)

两种写法执行后都会输出你期望的结果:

AfterMy Name is Praveen and Richardson

内容的提问来源于stack exchange,提问作者Selenium Lover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 05:55:18