Problem with groovy and regex matching groups

Viewed 2072

I'm getting here after reading some other questions and examples like:

Groovy syntax for regular expression matching

Groovy regex/pattern matching

Also this documentation I found online: https://e.printstacktrace.blog/groovy-regular-expressions-the-definitive-guide/

I was playing with it and I have what I think is a very basic regex but by some reason I always get no match.

So imagining I have a git url something like this: "ssh://git@bitbucket.sits.net/project/repo.git"

I want to extract in my groovy pipeline the project and repo itself: "ssh://git@bitbucket.sits.net/([a-zA-Z-]*)/([a-zA-Z-]*).git" (maybe there are smarter ways of doing this match but still should work)

Anyway the problem is that I'm testing this and at the moment I can't even make the simple ssh match, last alone my groups. It works fine in an online regex tester enter image description here

But it does not work in the groovy playground online.

This is the example (I'm testing it here https://groovy-playground.appspot.com/):

This input:

GIT_URL='ssh://git@bitbucket.sits.net/project/repo.git'

def match = GIT_URL =~ /ssh:\/\/git@bitbucket\.sits\.net\/([a-zA-Z-_]*)\/([a-zA-Z-_]*)\.git/

println match 

Outputs no match:

java.util.regex.Matcher[pattern=ssh://git@bitbucket\.sits\.net/([a-zA-Z-_]*)/([a-zA-Z-_]*)\.git region=0,45 lastmatch=]

I've tried a few things but not even ssh match works

GIT_URL='ssh://git@bitbucket.sits.net/project/repo.git'

def match = GIT_URL =~ /ssh/

println match 
java.util.regex.Matcher[pattern=ssh region=0,45 lastmatch=]

I thought it could be a problem in the tool but in my Jenkins pipeline it also does not work.

Also the example from the other question:

def match2 = "f1234" =~ /[a-z]\d{4}/
println match2
java.util.regex.Matcher[pattern=[a-z]\d{4} region=0,5 lastmatch=]
2 Answers

You can leave Groovy execute the right matcher method itself, just use

String GIT_URL='ssh://git@bitbucket.sits.net/project/repo.git'
def match = GIT_URL =~ /ssh:\/\/git@bitbucket\.sits\.net\/([a-zA-Z_-]*)\/([a-zA-Z_-]*)\.git/
if (match) { 
    println match[0][1]
    println match[0][2]
} else {
    println 'No match' 
}

See the Groovy demo.

With =~ operator, you actually tell Groovy to find partial matches inside longer strings, with ==~, you require full string match. All you need is if (match) to trigger matching. The match will contain all matches, so you get the first one via the zeroth index, and then you have an access to Group 1 via [1] and to Group 2 using [2].

Regex tip: always put - at the end of the character class if you mean to match a literal - char.

this was actually a bit not what I was expecting but I forgot to call the method matches()

GIT_URL='ssh://git@bitbucket.sits.net/project/repo.git'

def match = GIT_URL =~ /ssh:\/\/git@bitbucket\.sits\.net\/([a-zA-Z-_]*)\/([a-zA-Z-_]*)\.git/
match.matches()
println match.group(1)
println match.group(2)
project
repo
Related