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.
To check if a String matches a Pattern one should perform the following steps: Compile a String regular expression to a Pattern, using compile(String regex) API method of Pattern. Use matcher(CharSequence input) API method of Pattern to create a Matcher that will match the given String input against this pattern.
Using =~ operator in context of booleanregex. Matcher object in the context of the boolean expression (e.g., inside the if-statement.) In this case, Groovy implicitly invokes the matcher. find() method, which means that the expression evaluates to true if any part of the string matches the pattern.
A regular expression is a pattern that is used to find substrings in text. Groovy supports regular expressions natively using the ~”regex” expression. The text enclosed within the quotations represent the expression for comparison.
Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .
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
The negate regex match in Groovy should be
String regex = /^somedata(:somedata)*$/ assert !('somedata;somedata;somedata' ==~ regex) // assert success!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With