简体   繁体   中英

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.

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

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

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

def match = "somedata:somedata:somedata" ==~ /.+:.+:.+/

The negate regex match in Groovy should be

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

Was able to resolve this using:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM