Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a String matches a pattern in Groovy

Tags:

java

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.

like image 379
kicks Avatar asked Feb 12 '15 01:02

kicks


People also ask

How do you know if a string matches a pattern?

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.

What is =~ in Groovy?

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.

How do you write regex in Groovy?

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.

How do I match a pattern in regex?

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 "@" .


2 Answers

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

like image 168
Nick Grealy Avatar answered Oct 08 '22 05:10

Nick Grealy


The negate regex match in Groovy should be

 String regex = /^somedata(:somedata)*$/     assert !('somedata;somedata;somedata' ==~ regex)  // assert success! 
like image 36
TCH Avatar answered Oct 08 '22 05:10

TCH