How to check if a String matches a pattern in Groovy

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

Leave a Comment