Using Regular Expressions in Groovy

Regular expressions provide a powerful way to compare strings with patterns. These comparisons are often applied to validate data. For example, we might check a string to ensure that a phone number is provided in a particular format, say, area code in parentheses followed by the hypenated phone number. We will examine this scenario to show how you can tap into the power of regular expressions in your Groovy program.

To learn how to use regular expressions in Groovy follow these 3 steps:

  1. Open your text editor and type in the following lines of Groovy code:
    // Using Regular Expressions
    def phoneNumberValid = "(407) 555-1234"
    def phonePattern = ~/\(\d{3}\) \d{3}-\d{4}/
    println "Assert that $phoneNumberValid is stored as (999) 999-9999"
    testMatch = ( "$phoneNumberValid" =~ phonePattern )
    assert testMatch.matches()
    println "$phoneNumberValid is valid!"
    // Now test an invalid number (hyphen has been deleted!):
    def phoneNumberNOTValid = "(407) 5551234"
    println "Assert $phoneNumberNOTValid is stored as (999) 999-9999"
    testMatch = ( "$phoneNumberNOTValid" =~ phonePattern )
    assert testMatch.matches() 
    println "$phoneNumberNOTValid is valid!"
    // The following test will not be executed because the previous failure will cause the program to terminate
    println "Assert (again!) that $phoneNumberValid is stored as (999) 999-9999"
    testMatch = ( "$phoneNumberValid" =~ phonePattern )
    assert testMatch.matches()
    println "$phoneNumberValid is valid!"
    First, note the forward slash ("/") delimited string with a tilde ("~") prefix that is used when we define phonePattern. This syntax indicates that the string will be used as a pattern for a regular expression match operation. This syntax is useful because you do not have to escape any regular expression characters. In fact, the only character that requires an escape character (back slash, or "\") is the forward slash ("/"). A match operation tests the pattern against a string and is performed using the =~ operation. The result of the match can be obtained using the matches method. Here, we put the match test on an assert statement. The test will return false if the string did not conform to the pattern. The execution of the program will stop at that point because the assertion that the string conforms to the pattern is not true. Accordingly, the third and final test will not execute.
  2. Save your file as UsingRegularExpressions.groovy.
  3. In the command prompt, type in the command to interpret and run your script:
    Run regular expressions script
    The program output verifies that the first test was successful whereas the second test failed. As pointed out earlier, an assertion failure causes the program to terminate. Therefore, the third test was not executed.
Author: Stephen Withrow

Stephen has over 30 years of experience in training, development, and consulting in a variety of technology areas including Python, Java, C, C++, XML, JavaScript, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen has a degree in Computer Science and Physics from Florida State University.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.