View Category

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
clojure
(if (re-matches #"[A-Z][a-z]+" "Hello")
(println "ok"))
fsharp
if (Regex.IsMatch("Hello", "[A-Z][a-z]+")) then printfn "ok"
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'
java
if ("Hello".matches("[A-Z][a-z]+")) {
System.out.println("ok");
}
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/
clojure
(if-let [groups (re-matches #"one (.*) three" "one two three")]
(println (second groups)))
fsharp
let regmatch = (Regex.Match("one two three", "one (.*) three"))
if regmatch.Success then (printfn "%s" (regmatch.Groups.[1].Captures.[0].ToString()))
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
java
Pattern pattern = Pattern.compile("one (.*) three");
Matcher matcher = pattern.matcher("one two three");
if (matcher.matches()) {
System.out.println(matcher.group(1));
}
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+/
clojure
(if (re-find #"\d+" "abc 123 @#$")
(println "ok"))
fsharp
if (Regex.IsMatch("abc 123 @#$", "\\d+")) then printfn "ok"
groovy
if ('abc 123 @#$' =~ /\d+/) println 'ok'
if ('abc 123 @#$'.find(/\d+/)) println 'ok'
java
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
System.out.println("ok");
}
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+)/
clojure
(let [matcher (re-matcher #"\((\w+)\):(\d+)" "(fish):1 sausage (cow):3 tree (boat):4")]
(loop [match (re-find matcher)
lst []]
(if match
(recur (re-find matcher) (conj lst (str (second match) (nth match 2))))
lst)))
fsharp
let list = new ResizeArray<string>()
let mutable regmatch = (Regex.Match("(fish):1 sausage (cow):3 tree (boat):4", "\\((\\w+)\\):(\\d+)"))

while regmatch.Success do
list.Add(regmatch.Groups.[1].Captures.[0].ToString() ^ regmatch.Groups.[2].Captures.[0].ToString())
regmatch <- regmatch.NextMatch()
done

for word in list do printfn "%s" word done
// A solution without mutation:
let results =
Regex.Matches("(fish):1 sausage (cow):3 tree (boat):4", "\\((\\w+)\\):(\\d+)")
|> Seq.cast
|> Seq.map (fun (regmatch: Match) ->
regmatch.Groups.[1].Captures.[0].ToString() + regmatch.Groups.[2].Captures.[0].ToString()
)
|> List.ofSeq
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] }
java
List list = new ArrayList();
Pattern pattern = Pattern.compile("\\((\\w+)\\):(\\d+)");
Matcher matcher = pattern.matcher(text);
while(matcher.find()) {
list.add(matcher.group(1)+matcher.group(2));
}
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 "*"
clojure
(.replaceFirst (re-matcher #"e" "Red Green Blue") "*")
fsharp
let replaced = ((new Regex("e")).Replace("Red Green Blue", "*", 1))
printfn "%s" replaced
groovy
replaced = "Red Green Blue".replaceFirst("e", "*")
java
String replaced = "Red Green Blue".replaceFirst("e", "*");
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"
clojure
(.replaceAll (re-matcher #"se\w+" "She sells sea shells") "X")
fsharp
let replaced = ((new Regex("se\\w+")).Replace("She sells sea shells", "X"))
printfn "%s" replaced
groovy
replaced = text.replaceAll(/se\w+/,"X")
java
String replaced = text.replaceAll("se\\w+", "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+)\}/.
clojure
(def *string* "The {Quick} Brown {Fox}")
(def *regex* (re-pattern #"\{(\w+)\}"))

(println
(loop [result ""
src *string*
replace-strs (re-seq *regex* *string*)]
(if (empty? src)
result
(let [[match replacement] (first replace-strs)]
(if (= (first src) (first match))
; At the beginning of a sequence that should be replaced.
; Do replacement of a single match
(recur (str result (apply str (reverse replacement)))
(drop (count match) src)
(rest replace-strs))
; else, just copy one char from the source to the result
(recur (str result (first src))
(rest src)
replace-strs))))))
(clojure.string/replace "The {Quick} Brown {Fox}"
#"\{(\w+)\}"
(fn [[_ word]] (apply str (reverse word))))
fsharp
open System
open System.Text.RegularExpressions
let reverseMatch (m:Match) =
String(m.Groups.[1].Value.ToCharArray() |> Array.rev)
let output = Regex.Replace("The {Quick} Brown {Fox}", @"\{(\w+)\}", reverseMatch)
groovy
replaced = "The {Quick} Brown {Fox}".replaceAll(/\{(\w+)\}/, { full, word -> word.reverse() } )
java
Matcher m = Pattern.compile("\\{(\\w+)\\}").matcher("The {Quick} Brown {Fox}");
StringBuffer sb = new StringBuffer(32), rsb = new StringBuffer(8);

while (m.find())
{
rsb.replace(0, rsb.length(), m.group(1)); rsb.reverse(); m.appendReplacement(sb, rsb.toString());
}
m.appendTail(sb);
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)