Skip to content

Regular Expressions

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

Creating a Regular Express

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!!!

Clone this wiki locally