我正在使用一些古老的版本控制,并试图使用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 .

谢谢,