View Category

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
fantom
if (Regex<|[A-Z][a-z]+|>.matches("Hello"))
echo("ok")

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
fantom
m := Regex<|one (.*) three|>.matcher("one two three")
if (m.matches)
echo("${m.group(1)}")

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
fantom
m := Regex<|\d+|>.matcher("abc 123 @#\$")
if (m.find)
echo("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+)/
fantom
m := Regex<|\((\w+)\):(\d+)|>.matcher(s)
list := Str[,]
while (m.find) { list.add("${m.group(1)}${m.group(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 "*"
fantom
replaced := Regex<|e|>.split("Red Green Blue",2).join("*")

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"
fantom
replaced := Regex<|se\w+|>.split("She sells sea shells").join("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+)\}/.
fantom
s := "The {Quick} Brown {Fox}"
m := Regex<|\{(\w+)\}|>.matcher(s)
buf := StrBuf(s.size)
last := 0
while (m.find)
{
buf.add(s[last..m.start-1]).add(m.group(1).reverse)
last = m.end
}
buf.add(s[last..-1])
replaced := buf.toStr