【问题标题】:Regex to replace string between dashes (groovy)正则表达式替换破折号之间的字符串(groovy)
【发布时间】:2014-04-15 11:23:32
【问题描述】:

我在 groovy 中有一个方法,它接收以下格式的字符串:

def src = "a.b.c-constant-qualifier"
def update = "test"

我正在尝试提出一个正则表达式,它将 -???- 之间的内容替换为更新后的字符串。在上述情况下,结果应该是:

字符串结果 = "a.b.c-test-qualifier"

我目前这样做:

def update ="-test-" 
def src = "a.b.c-constant-qualifier"
def result = (src =~ /-constant-/).replaceFirst(update)

只要源字符串包含"-constant-" 字符串,它就可以工作。但是如何让我的正则表达式工作,以便用更新字符串替换两个破折号之间的任何内容?

【问题讨论】:

    标签: regex groovy


    【解决方案1】:

    只需这样做:

    def update ="-test-"
    def src = "a.b.c-constant-qualifier"
    def result = (src =~ /-[^-]*-/).replaceFirst(update)
    

    演示:http://regex101.com/r/rZ3nJ0

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-28
      • 1970-01-01
      相关资源
      最近更新 更多