View Category

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
scala
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/
scala
val m = Pattern.compile("one (.*) three").matcher("one two three")
if (m.matches) println(m.group(1))

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
scala
if (Pattern.compile("\\d+").matcher("abc 123 @#$").find) 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+)/
scala
val m = Pattern.compile("\\((\\w+)\\):(\\d+)").matcher("(fish):1 sausage (cow):3 tree (boat):4")
var list : List[String] = Nil

while (m.find) list = (m.group(1) + m.group(2)) :: list ; list = list.reverse

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 "*"
scala
val 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"
scala
val replaced = "She sells sea shells".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+)\}/.
scala
val m = Pattern.compile("\\{(\\w+)\\}").matcher("The {Quick} Brown {Fox}")
val sb = new StringBuffer(32) ; val rsb = new StringBuffer(8)

while (m.find) { rsb.replace(0, rsb.length, m.group(1)) ; m.appendReplacement(sb, rsb.reverse.toString) }
m.appendTail(sb)