kicks
kicks

Reputation: 557

How to check if a String matches a pattern in Groovy

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

Answers (4)

Nick Grealy
Nick Grealy

Reputation: 25922

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

Upvotes: 49

TCH
TCH

Reputation: 81

The negate regex match in Groovy should be

 String regex = /^somedata(:somedata)*$/   
 assert !('somedata;somedata;somedata' ==~ regex)  // assert success!

Upvotes: 7

kicks
kicks

Reputation: 557

Was able to resolve this using:

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

Upvotes: -5

cangoektas
cangoektas

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

Related Questions