Reputation: 557
How do I check if a string matches a pattern in groovy? My pattern is "somedata:somedata:somedata", and I want to check if this string format is followed. Basically, the colon is the separator.
Upvotes: 43
Views: 93823
Reputation: 25922
Groovy regular expressions have a ==~
operator which will determine if your string matches a given regular expression pattern.
// ==~ 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
http://docs.groovy-lang.org/latest/html/documentation/#_match_operator
Upvotes: 49
Reputation: 81
The negate regex match in Groovy should be
String regex = /^somedata(:somedata)*$/
assert !('somedata;somedata;somedata' ==~ regex) // assert success!
Upvotes: 7
Reputation: 719
Try using a regular expression like .+:.+:.+
.
import java.util.regex.Matcher
import java.util.regex.Pattern
def match = "somedata:somedata:somedata" ==~ /.+:.+:.+/
Upvotes: 4