View Category

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
groovy
if ("Hello" =~ /[A-Z][a-z]+/) println 'ok'
if ("Hello".find(/[A-Z][a-z]+/)) println 'ok'
// with precompiled regex
def regex = ~/[A-Z][a-z]+/
if ("Hello".find(regex)) println 'ok'
// with precompiled regex
def regex = ~/[A-Z][a-z]+/
if ("Hello".matches(regex)) println 'ok'
if ("Hello".matches("[A-Z][a-z]+")) println 'ok'

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
groovy
matcher = ("one two three" =~ /one (.*) three/)
if (matcher) println matcher[0][1]
match = "one two three".find("one (.*) three") { it[1] }
if (match) println match

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
groovy
if ('abc 123 @#$' =~ /\d+/) println 'ok'
if ('abc 123 @#$'.find(/\d+/)) println 'ok'

Loop through a string matching a regex and performing an action for each match

Create a list [fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/
groovy
list = (text =~ /\((\w+)\):(\d+)/).collect{ it[1] + it[2] }
list = []
text.eachMatch(/\((\w+)\):(\d+)/){
list << it[1] + it[2]
}
list = []
text.eachMatch(/\((\w+)\):(\d+)/){ m, name, number ->
list << "$name$number"
}
list = (text =~ /\((\w+)\):(\d+)/).collect{ all, name, num -> "$name$num" }
list = text.findAll(regex){ _, name, num -> "$name$num" }
list = text.findAll(regex){ it[1] + it[2] }

Replace the first regex match in a string with a static string

Transform "Red Green Blue" into "R*d Green Blue" by replacing /e/ with "*"
groovy
replaced = "Red Green Blue".replaceFirst("e", "*")

Replace all regex matches in a string with a static string

Transform "She sells sea shells" into "She X X shells" by replacing /se\w+/ with "X"
groovy
replaced = text.replaceAll(/se\w+/,"X")

Replace all regex matches in a string with a dynamic string

Transform "The {Quick} Brown {Fox}" into "The kciuQ Brown xoF" by reversing words in braces using the regex /\{(\w+)\}/.
groovy
replaced = "The {Quick} Brown {Fox}".replaceAll(/\{(\w+)\}/, { full, word -> word.reverse() } )