Skip to content

Regular Expressions

Philip Ford edited this page Apr 23, 2017 · 6 revisions
def result = 'abc' =~ /[a-z]+/
result.matches()  // TRUE

Creating a Regular Expression

Surround a string with forward slashes (/) to make it a pattern, just like in JavaScript.

Operators

  • ”~” - used before a string and it will cause the string to be compiled to a Pattern for later use

    // \b means word boundary, [A-Z] means any capital letter, + means one or more
    // so this matches any string of one or more capital letter with a word boundary (non-word character) on either side of it
    def shoutedWord = ~/\b[A-Z]+\b/   
  • ”=~” - Creates a Matcher out of the String on the left hand side and the Pattern on the right.

    def matcher = ("EUREKA" =~ shoutedWord)  
    assert matcher.matches()         // TRUE
    
    def numberMatcher = "1234" =~ /\d+/  
    assert numberMatcher.matches()   // TRUE
  • ”==~” - Returns a boolean that specifies if the full String matches the Pattern

    assert "1234" ==~ /\d+/    // TRUE
    assert "FOO2" ==~ /\d+/    // FALSE!!!

Strings

Groovy Strings have replace and replaceAll methods.

Collections

Groovy also makes significant additions to what you can do with Collections. In addition to each, collect, inject, etc, there is a regular expression aware iterator called grep that will pass each item in the Collection through a filter and return a subset of items that match the filter. We can use a regular expression as a filter:

// regular expression says 0 or more characters (".*") followed by the string "bar" that is at the end of the string ("$")
assert ["foobar", "bazbar"] == ["foobar", "bazbar", "barquux"].grep(~/.*bar$/)

You can achieve the same thing with findAll but it takes a little more typing:

assert ["foobar", "bazbar"] == ["foobar", "bazbar", "barquux"].findAll { it ==~ /.*bar$/ } 

References

Clone this wiki locally