Philip Stefanov Philip Stefanov - 9 days ago 7
Groovy Question

Groovy String replacement with link

I have multi-lines string from git log in variable
and want to replace matched lines with hyper-links
but keep some parts of the original string with Groovy.


Example:

commit 7a1825abc69f1b40fd8eb3b501813f21e09bfb54
Author: Filip Stefanov
Date: Mon Nov 21 11:05:08 2016 +0200

TICKET-1

Test change

Change-Id: I7b4028e504de6c4a48fc34635d4b94ad038811a6


Should look like:

commit 7a1825abc69f1b40fd8eb3b501813f21e09bfb54
Author: Filip Stefanov
Date: Mon Nov 21 11:05:08 2016 +0200

<a href=http://localhost:8080/browse/TICKET-1>TICKET-1</a>

Test change

<a href=http://localhost:8081/#/q/I7b4028e504de6c4a48fc34635d4b94ad038811a6,n,z>Change-Id: I7b4028e504de6c4a48fc34635d4b94ad038811a6</a>


Im pretty bad in Groovy regex dont know how to use grouping or closures so far so good:

mystring.replaceAll(/TICKET-/, "http://localhost:8080/browse/TICKET-")


NOTE:
TICKET {int} and Change-Id {hash} are variables

Answer
mystring.replaceAll(/(TICKET-\d++)/, '<a href="http://localhost:8080/browse/$1">$1</a>')
        .replaceAll(/Change-Id: (I\p{XDigit}++)/, '<a href="http://localhost:8081/#/q/$1,n,z">Change-Id: $1</a>')

Of course you have to replace the dynamic parts accordingly. Currently it is at least one digit after the TICKET- and an I and then at least one hex digit after the Change-ID:.