39

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.

Mark
  • 1,788
  • 1
  • 22
  • 21
kicks
  • 517
  • 1
  • 4
  • 3

4 Answers4

43

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

Nick Grealy
  • 24,216
  • 9
  • 104
  • 119
  • 2
    The old groovy.codehouse.org site is expired. Try this: http://docs.groovy-lang.org/latest/html/documentation/#_regular_expression_operators – MarkHu Apr 04 '17 at 23:21
  • 1
    The 'assert not matches' examples should look like this: `assert !("somedata:xxxxxxxx:somedata" ==~ regex)`. `!=~` is not a valid operator to negate a regex match: https://groovy-lang.org/operators.html#_regular_expression_operators – Joman68 Feb 09 '21 at 23:27
  • @Joman68 - just tried it over here https://www.tutorialspoint.com/execute_groovy_online.php (Groovy 2.4.8) - code works fine. Have you tried it? Can you provide a reproducible example? – Nick Grealy Feb 10 '21 at 02:52
  • @NickGrealy reproducible example here: https://groovyconsole.appspot.com/script/5129310184669184 – Joman68 Feb 19 '21 at 01:19
  • Also see https://stackoverflow.com/a/19858242/3059685 and https://stackoverflow.com/a/31220106/3059685 – Joman68 Feb 19 '21 at 01:38
5

The negate regex match in Groovy should be

 String regex = /^somedata(:somedata)*$/   
 assert !('somedata;somedata;somedata' ==~ regex)  // assert success!
TCH
  • 51
  • 1
  • 4
4

Try using a regular expression like .+:.+:.+.

import java.util.regex.Matcher
import java.util.regex.Pattern

def match = "somedata:somedata:somedata" ==~ /.+:.+:.+/
cangoektas
  • 679
  • 5
  • 7
-5

Was able to resolve this using:

myString.matches("\S+:\S+:\S+")

kicks
  • 517
  • 1
  • 4
  • 3