替换groovy中的捕获组

时间:2018-03-01 15:13:09

标签: regex groovy

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

我的目标字符串可以从其中那里开始,然后可以跟任意数量的。(点字符)和单词。我需要用_(下划线)

替换所有。(点字符)

任何不以 开头的

示例字符串是

    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

预期输出

    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

我能够匹配确切的模式。使用/(where|there)\.((\w+)(\.))+/,但当我使用replaceAll时,我的结果不正确。

1 个答案:

答案 0 :(得分:2)

您可以使用

/(\G(?!\A)\w+|\b(?:where|there)\b)\./

或者如果你只需要处理这两个字:

/(\G(?!\A)\w+|\b[wt]here\b)\./

替换为$1_。请参阅regex demo

<强>详情

  • (\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 demo

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_')

输出:

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
相关问题