替换groovy中的捕获组

Sou*_*h K 3 regex groovy

我是 groovy 的新手,一直在尝试这个

我的目标字符串可以以whereThere开头,后面可以跟任意数量的 .(点字符)和单词。我需要将所有.(点字符)替换为 _(下划线)

任何不以whereThere开头的内容都不应该被替换

示例字符串是

    hey where.is.the book on.brown.table 
    hey there.is.a.boy.in.the city Delhi
    hey here.is.the.boy living next door
Run Code Online (Sandbox Code Playgroud)

预期输出是

    hey where_is_the book on.brown.table 
    hey there_is_a_boy_in_the city Delhi
    hey here.is.the.boy living next door
Run Code Online (Sandbox Code Playgroud)

我能够匹配精确的模式。使用/(where|there)\.((\w+)(\.))+/,但是当我使用 时,replaceAll我最终得到了不正确的结果。

Wik*_*żew 5

您可以使用

/(\G(?!\A)\w+|\b(?:where|there)\b)\./
Run Code Online (Sandbox Code Playgroud)

或者,如果您只需要处理这两个词:

/(\G(?!\A)\w+|\b[wt]here\b)\./
Run Code Online (Sandbox Code Playgroud)

用。。。来代替$1_。请参阅正则表达式演示

细节

  • (\G(?!\A)\w+|\b(?:where|there)\b)- 第 1 组捕获:
    • \G(?!\A)\w+|- 上一个匹配的结尾 ( \G(?!\A)),然后是 1+ 个单词字符 ( \w+),或者
    • \b(?:where|there)\b- 一个wherethere整个单词(你甚至可以写得好像\b[tw]here\b只需要处理这两个单词一样)
  • \.- 一个点。

请参阅Groovy 演示

String s = "hey where.is.the book on.brown.table\nhey there.is.a.boy.in.the city Delhi\nhey here.is.the.boy living next door"
print s.replaceAll(/(\G(?!\A)\w+|\b(?:where|there)\b)\./, '$1_')
Run Code Online (Sandbox Code Playgroud)

输出:

hey where_is_the book on.brown.table
hey there_is_a_boy_in_the city Delhi
hey here.is.the.boy living next door
Run Code Online (Sandbox Code Playgroud)