0

I'm writing Jenkins pipeline in which I'm extracting Jira tickets from GIT commit message.I'm using JIRA ID regex. How can I process a multiline string? I also have to display commit messages which do not contain any valid ticket ID's. How can I do that using the if-else loop in groovy? Below logic works for a single line, but not working for multi-line.

def commit = """new change
CO-10389
SRE-1234"""

def regex = (/[\s|]?([A-Z]+-[0-9]+)[\s:|]?/) 

if(commit =~ regex){
    def jira = commit.readLines().findAll(/[\s|]?([A-Z]+-[0-9]+)[\s:|]?/)
    println jira
} else {
    println commit
}
daggett
  • 26,404
  • 3
  • 40
  • 56
Chaitali
  • 87
  • 13
  • Does this answer your question? [regex over multiple lines in Groovy](https://stackoverflow.com/questions/1363643/regex-over-multiple-lines-in-groovy) – injecteer Jan 24 '20 at 12:34
  • Thanks for the suggestion. The above answer helped me to process multiple lines. Is there any way to apply the if-else loop in groovy regex? I want to capture the string which is not matching the regex in else loop. – Chaitali Jan 27 '20 at 11:42

1 Answers1

2

Multiline regex won't help you if you want to process also mis-matching lines, so you should be processing your text line-by-line:

import java.util.regex.Matcher

def commit = """new change
CO-10389
CO-
SRE-1234"""

commit.eachLine{ l ->
  switch( l ){
    case ~/[\s|]?([A-Z]+-[0-9]+)[\s:|]?[\s|]?.*/:
      //println "JIRA: ${Matcher.lastMatcher[0][1]}"
      // or
      println "JIRA: ${( l =~ /[\s|]?([A-Z]+-[0-9]+)[\s:|]?.*/ )[0][0]}"
      break
    default:
      println "no JIRA $l"
  }
}

prints

no JIRA new change
JIRA: CO-10389
no JIRA CO-
JIRA: SRE-1234
injecteer
  • 20,038
  • 4
  • 45
  • 89
  • I am getting: No such field found: field java.lang.Class lastMatcher. Any idea how to solve that? – Oplop98 Oct 04 '21 at 21:09
  • should be something with your groovy version. Anyway see the updated answer – injecteer Oct 04 '21 at 21:23
  • Thank you ! One more question.. If the commit message looks like 'CO-10389: some text', this code is not pulling the Jira ticket. Any workaround for that? – Oplop98 Oct 04 '21 at 21:25
  • add `.*` to the end of your regexp, but the extra text won't be selected by regex. see update – injecteer Oct 04 '21 at 21:28