首页 > 解决方案 > 使用空参数简化 groovy 子字符串调用

问题描述

我正在使用一些过时的版本控制,并尝试使用 Groovy 解析评论以供 Jenkins 使用。

我设法让 Groovy 代码工作,但想知道是否有办法简化代码。

我使用的测试字符串如下:

text = "IL!21234 12/3/18 3:46 PM user_d Some comments with new\nlines interspersed and pointers to commits\n(IL!1234)\nIL!1234 1/2/17 2:46 AM user_x Some other commit\n"

预期结果是:

tasks = ["IL!21234 12/3/18 3:46 PM user_d Some comments with new lines interspersed and pointers to commits (IL!1234)", "IL!1234 1/2/17 2:46 AM user_x Some other commit"]

下面是我的代码:

m = (text =~ /IL!\d+ \d{1,2}\/\d{1,2}\/\d{1,2} \d{1,2}:\d{1,2} [AP]M [a-z_]* .*/)
matchStarts = []
tasks = []

while(m.find()) {
  matchStarts << m.start()
}

matchStarts.eachWithIndex { matchStart, index ->
  if (matchStarts[index + 1]) {
    tasks << text.substring(matchStart, matchStarts[index + 1]).replace("\n", " ").trim()
  } else {
    tasks << text.substring(matchStart).replace("\n", " ").trim()
  }
}

这行得通,但我想知道是否有更好的方法来处理 if/else。

谢谢,

标签: if-statementgroovysubstringsimplify

解决方案


推荐阅读