Skip to content

Instantly share code, notes, and snippets.

@bdkosher
Last active December 17, 2015 16:29
Show Gist options
  • Save bdkosher/5639262 to your computer and use it in GitHub Desktop.
Save bdkosher/5639262 to your computer and use it in GitHub Desktop.
Regular expression literals are just String literals
// a regex literal is just a String literal with '/' deliminters and backslash-friendliness
def rx1 = /^foo$/
assert rx1.class == String.class
assert 'foo' ==~ rx1
assert 'FOO' !=~ rx1
assert 'Foo' !=~ rx1
// so you can use String methods and operators on them
def rx2 = /(?i)/ + rx1
assert 'foo' ==~ rx2
assert 'FOO' ==~ rx2
assert 'Foo' ==~ rx2
// and methods that accept Strings as args can use "regular expression."
def b = new StringBuilder()
b.append(/Hello, world!/)
assert 'Hello, world!' == b.toString()
// You could use GroovyStrings to interpolate "regular expressions"
// (be careful to escape backslashes and dollar signs, though)
def matchValue = 'ba[r|z]'
def grx = "^${matchValue}\$"
assert 'bar' ==~ grx
assert 'baz' ==~ grx
assert 'foo' !=~ grx
// but interpolation works inside the slashy-Strings
def file = 'test.txt'
def path = /C:\Users\jwolf2\Desktop\${file}/
assert (/C:\Users\jwolf2\Desktop\test.txt/ == path) // parens necessary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment