Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

The Groovy Language


[ 64 ]

"We don't need to escape quotes in a multi-line string"
'''
def name = "Daniel Dewdney"
def customerSelectSQL = """
select * from customer where name = ('${name}');
"""
expect:
multiLine instanceof String
customerSelectSQL instanceof GString

Multiline strings are useful for embedding XML, HTML, and SQL. Combined with
GStrings, they are ideal for building templates in our code.


Regular expressions


Groovy supports regular expressions natively within the language. There are three
built-in convenience operators specifically for this purpose:



  • The regex match operator, ==~

  • The regex find operator, =~

  • The regex pattern operator, ~String


The match operator is a simple Boolean operator that takes the operands
String ==~ regex string. The match returns true if the string operand is a match
to the regex string. Regex strings are a sequence of characters that define a pattern
to apply when searching for a match within a string. They can consist of specific
characters or character classes, such as \d (any digit), and \w (any word character).
Later, we'll look at a table with some of the more commonly-used character classes.


In the simplest case, a regular expression can just consist of a sequence of regular
characters. So, a regex string Match Me will match only strings containing exactly
the characters Match Me. In other words, it can be used to just test equality. We can
use this feature to show how the different ways of expressing strings in Groovy
result in the same string:


given: "A String we want to match"
def matchMe = "Match Me"
expect: "We can do an exact match using single quoted Strings"
matchMe ==~ 'Match Me'
and: "using multiline style String"
matchMe ==~ """Match Me"""
and: "using slashy String"
matchMe ==~ /Match Me/

http://www.ebook3000.com
Free download pdf