Groovy regular expressions have a ==~ operator which will determine if your string matches a given regular expression pattern.
Example
// ==~ tests, if String matches the pattern
assert "2009" ==~ /\d+/ // returns TRUE
assert "holla" ==~ /\d+/ // returns FALSE
Using this, you could create a regex matcher for your sample data like so:
// match 'somedata', followed by 0-N instances of ':somedata'...
String regex = /^somedata(:somedata)*$/
// assert matches...
assert "somedata" ==~ regex
assert "somedata:somedata" ==~ regex
assert "somedata:somedata:somedata" ==~ regex
// assert not matches...
assert "somedata:xxxxxx:somedata" !=~ regex
assert "somedata;somedata;somedata" !=~ regex
Read more about it here:
http://docs.groovy-lang.org/latest/html/documentation/#_match_operator
Answer from Nick Grealy on Stack OverflowGroovy regular expressions have a ==~ operator which will determine if your string matches a given regular expression pattern.
Example
// ==~ tests, if String matches the pattern
assert "2009" ==~ /\d+/ // returns TRUE
assert "holla" ==~ /\d+/ // returns FALSE
Using this, you could create a regex matcher for your sample data like so:
// match 'somedata', followed by 0-N instances of ':somedata'...
String regex = /^somedata(:somedata)*$/
// assert matches...
assert "somedata" ==~ regex
assert "somedata:somedata" ==~ regex
assert "somedata:somedata:somedata" ==~ regex
// assert not matches...
assert "somedata:xxxxxx:somedata" !=~ regex
assert "somedata;somedata;somedata" !=~ regex
Read more about it here:
http://docs.groovy-lang.org/latest/html/documentation/#_match_operator
The negate regex match in Groovy should be
String regex = /^somedata(:somedata)*$/
assert !('somedata;somedata;somedata' ==~ regex) // assert success!
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