View Category

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
ruby
puts "ok" if ("Hello"=~/^[A-Z][a-z]+$/)
java
if ("Hello".matches("[A-Z][a-z]+")) {
System.out.println("ok");
}
perl
print 'ok' if ('Hello' =~ /[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'
scala
if ("Hello".matches("[A-Z][a-z]+")) println("ok")
python
found = re.match(r'[A-Z][a-z]+', 'Hello')
if found:
print 'ok'
cpp
if ((gcnew Regex("[A-Z][a-z]+"))->IsMatch("Hello")) Console::WriteLine("ok");
if (Regex::IsMatch("Hello", "[A-Z][a-z]+")) Console::WriteLine("ok");
Regex^ rx = gcnew Regex("[A-Z][a-z]+");
if (rx->IsMatch("Hello")) Console::WriteLine("ok");
cmatch what;
if (regex_match("Hello", what, regex("[A-Z][a-z]+")))
cout << "ok" << endl;
fsharp
if (Regex.IsMatch("Hello", "[A-Z][a-z]+")) then printfn "ok"
erlang
String = "Hello", Regexp = "[A-Z][a-z]+",
is_match(String, Regexp) andalso (begin io:format("ok~n"), true end).
case re:run("Hello", "[A-Z][a-z]+") of {match, _} -> ok end.
ocaml
if Str.string_match (Str.regexp "[A-Z][a-z]+") "Hello" 0
then print_string "ok";;
csharp
if (Regex.IsMatch("Hello", "[A-Z][a-z]+"))
{
Console.WriteLine("ok");
}
php
if(ereg('[A-Za-z]+', 'Hello')) {
echo "ok";
}
if(preg_match('/[A-Za-z]+/', 'Hello')>0) {
echo "ok";
}
haskell
import Text.Regex.Posix
main = if "Hello" =~ "[A-Z][a-z]+" then putStrLn "OK" else return ()
clojure
(if (re-matches #"[A-Z][a-z]+" "Hello")
(println "ok"))
fantom
if (Regex<|[A-Z][a-z]+|>.matches("Hello"))
echo("ok")
go
result, _ := regexp.MatchString("[A-Z][a-z]+", "Hello")
if result {
fmt.Println("ok")
}

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
ruby
puts $1 if "one two three"=~/^one (.*) three$/
java
Pattern pattern = Pattern.compile("one (.*) three");
Matcher matcher = pattern.matcher("one two three");
if (matcher.matches()) {
System.out.println(matcher.group(1));
}
perl
print $1 if "one two three"=~/^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
scala
val m = Pattern.compile("one (.*) three").matcher("one two three")
if (m.matches) println(m.group(1))
python
match = re.match(r'one (.*) three', 'one two three')
if match:
print match.group(1)
cpp
Match^ match = Regex::Match("one two three", "one (.*) three");
if (match->Success) Console::WriteLine("{0}", match->Groups[1]->Captures[0]);
cmatch what;
if (regex_match("one two three", what, regex("one (.*) three")))
cout << what[1] << endl;
fsharp
let regmatch = (Regex.Match("one two three", "one (.*) three"))
if regmatch.Success then (printfn "%s" (regmatch.Groups.[1].Captures.[0].ToString()))
erlang
case re:run("one two three", "one (.*) three", [{capture, [1], list}]) of {match, Res} -> hd(Res) end.
ocaml
#load "str.cma" ;;

let s = "one two three" in
if Str.string_match (Str.regexp "one \\(.*\\) three") s 0 then
print_string (Str.matched_group 1 s)
csharp
using System;
using System.Text.RegularExpressions;

public class RegexBackReference {
public static void Main() {
var oneTwoThree = "one two three";
var pattern = "one (.*) three";

Match match = Regex.Match(oneTwoThree, pattern);

// group 0 is the entire match. 1 is the first backreference
Console.WriteLine(match.Groups[1]);
}
}
php
preg_match('/one (.*) three/', 'one two three', $matches);
echo $matches[1];
ereg('one (.*) three', 'one two three', $regs);
echo $regs[1];
haskell
import Text.Regex
main = case matchRegex (mkRegex "one (.*) three") "one two three" of
Nothing -> return ()
Just (x:_) -> putStrLn x
clojure
(if-let [groups (re-matches #"one (.*) three" "one two three")]
(println (second groups)))
fantom
m := Regex<|one (.*) three|>.matcher("one two three")
if (m.matches)
echo("${m.group(1)}")
go
re, _ := regexp.Compile("one (.*) three")
groups := re.FindStringSubmatch("one two three")
if len(groups) > 0 {
fmt.Println(groups[1])
}

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
ruby
puts "ok" if (text=~/\d+/)
java
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
System.out.println("ok");
}
perl
print "ok" if ("abc 123 @#\$" =~ m/\d+/)
groovy
if ('abc 123 @#$' =~ /\d+/) println 'ok'
if ('abc 123 @#$'.find(/\d+/)) println 'ok'
scala
if (Pattern.compile("\\d+").matcher("abc 123 @#$").find) println("ok")
python
found = re.search(r'\d+', 'abc 123 @#$')
if found:
print 'ok'
cpp
if (Regex::IsMatch("abc 123 @#$", "\\d+")) Console::WriteLine("ok");
fsharp
if (Regex.IsMatch("abc 123 @#$", "\\d+")) then printfn "ok"
erlang
% Erlang uses 'egrep'-compatible regular expressions, so shortcuts like '\d' not supported
String = "abc 123 @#$", Regexp = "[0-9]+",
is_match(String, Regexp) andalso (begin io:format("ok~n"), true end).
case re:run("abc 123 @#$", "\\d+") of {match, _} -> ok end.
ocaml
#load "str.cma" ;;

let re = Str.regexp "[0-9]+" in
try let _ = Str.search_forward re "abc 123 @#$" 0 in
print_string "ok"
with _ -> ()
csharp
if(System.Text.RegularExpressions.Regex.IsMatch("abc 123 @#$",@"\d+")){
Console.WriteLine("ok");
}
php
if (preg_match("/\d+/", "abc 123 @#$"))
echo "ok";
haskell
import Text.Regex
main = case matchRegex (mkRegex "\d+") "abc 123 @#$" of
Nothing -> putStrLn "not ok"
Just _ -> putStrLn "ok"
clojure
(if (re-find #"\d+" "abc 123 @#$")
(println "ok"))
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+)/
ruby
list = text.scan(/\((\w+)\):(\d+)/).collect{|x| x.join}
list=[]
text.scan(/\((\w+)\):(\d+)/) {
list << $1+$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));
}
perl
while ($text =~ /\((\w+)\):(\d+)/g) {
push @list, "$1$2"
}
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] }
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
python
map(''.join, re.findall(r"\((\w+)\):(\d+)", "(fish):1 sausage (cow):3 tree (boat):4"))
--------------------------------------------------------------------------
(''.join(m.groups()) for m in re.finditer(r"\((\w+)\):(\d+)", "(fish):1 sausage (cow):3 tree (boat):4"))
cpp
Match^ match = Regex::Match("(fish):1 sausage (cow):3 tree (boat):4", "\\((\\w+)\\):(\\d+)");

while (match->Success)
{
list->Add(match->Groups[1]->Captures[0]->ToString() + match->Groups[2]->Captures[0]->ToString());
match = match->NextMatch();
}
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
erlang
solve(S) ->
R = "\\((\\w+?)\\):(\\d+)",
{match, M} = re:run(S,R, [global, {capture, all_but_first, list}]),
[ A++N || [A, N] <- M].
ocaml
let result =
let str = "(fish):1 sausage (cow):3 tree (boat):4" in
let ms = Pcre.exec_all ~pat:"\\((\\w+)\\):(\\d+)" str in
Array.to_list (
Array.map (fun m ->
let s = Pcre.get_substrings m in
Printf.sprintf "%s%s" s.(1) s.(2);
) ms
)
csharp
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public static class extensions {
public static IList<string> Map(this string me, string pattern, Func<Match, string> action){
IList<string> matches = new List<string>();
foreach (Match match in Regex.Matches(me,pattern)){
matches.Add(action(match));
}
return matches;
}
}

class Test
{
static void Main()
{
IList<string> list = "(fish):1 sausage (cow):3 tree (boat):4".Map(@"\((\w+)\):(\d+)", (m) => {return m.Groups[1].Value + m.Groups[2].Value;});
}
}
php
preg_match_all("/\((\w+)\):(\d+)/", "(fish):1 sausage (cow):3 tree (boat):4", $matches);
for ($i=0, $c=count($matches[0]); $i < $c; $i++) {
$list[] = $matches[1][$i].$matches[2][$i];
}
haskell
import Text.Regex

getParenNum s = case matchRegexAll re s of
Nothing -> []
Just (_,_,after,[word,num]) -> (word ++ num):getParenNum after where
re = mkRegex "\\((\\w+)\\):([[:digit:]]+)"

main = putStrLn (show (getParenNum "(fish):1 sausage (cow):3 tree (boat):4"))
import Text.Regex

getParenNum :: String -> Maybe (String, String, String, [String])
getParenNum s = matchRegexAll re s
where re = mkRegex "\\((\\w+)\\):([[:digit:]]+)"

main = putStrLn (show (getParenNum "(fish):1 sausage (cow):3 tree (boat):4"))
import Text.Regex

getParenNum :: String -> Maybe (String, String, String, [String])
getParenNum s = matchRegexAll re s
where re = mkRegex "\\((\\w+)\\):([[:digit:]]+)"

main = putStrLn . show . getParenNum $ "(fish):1 sausage (cow):3 tree (boat):4"
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)))
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 "*"
ruby
p "Red Green Blue".sub(/e/,'*')
java
String replaced = "Red Green Blue".replaceFirst("e", "*");
perl
$text =~s/e/*/;
groovy
replaced = "Red Green Blue".replaceFirst("e", "*")
scala
val replaced = "Red Green Blue".replaceFirst("e", "*")
python
print re.sub(r'e', '*', 'Red Green Blue', 1)
cpp
String^ Replaced = (gcnew Regex("e"))->Replace("Red Green Blue", "*", 1);
fsharp
let replaced = ((new Regex("e")).Replace("Red Green Blue", "*", 1))
printfn "%s" replaced
erlang
{ok, Replaced, _} = regexp:sub("Red Green Blue", "e", "*"),
re:replace("Red Green Blue", "e", "*", [{return, list}]).
ocaml
let replaced = Str.replace_first (Str.regexp "e") "*" "Red Green Blue" in
print_endline replaced ;;
php
echo preg_replace('/e/', '*', "Red Green Blue", 1);
clojure
(.replaceFirst (re-matcher #"e" "Red Green Blue") "*")
fantom
replaced := Regex<|e|>.split("Red Green Blue",2).join("*")
go
i := 0
f := func (in string) (out string) {
i++
if i == 1 {
return "*"
}
return in
}

re, _ := regexp.Compile("e")
s := re.ReplaceAllStringFunc("Red Green Blue", f)
fmt.Println(s)

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"
ruby
replaced = text.gsub(/se\w+/,"X")
java
String replaced = text.replaceAll("se\\w+", "X");
perl
$text = "She sells sea shells";
$text =~ s/se\w+/X/g;
groovy
replaced = text.replaceAll(/se\w+/,"X")
scala
val replaced = "She sells sea shells".replaceAll("se\\w+", "X")
python
transformed = re.sub(r'se\w+', 'X', 'She sells sea shells')
cpp
String^ Replaced = (gcnew Regex("se\\w+"))->Replace("She sells sea shells", "X");
String^ Replaced = Regex::Replace("She sells sea shells", "se\\w+", "X");
fsharp
let replaced = ((new Regex("se\\w+")).Replace("She sells sea shells", "X"))
printfn "%s" replaced
erlang
% Erlang uses 'egrep'-compatible regular expressions, so shortcuts like '\w' not supported
{ok, Replaced, _} = regexp:gsub("She sells sea shells", "se[A-Za-z0-9_]+", "X"),
re:replace("She sells sea shells", "se\\w+", "X", [global, {return, list}]).
ocaml
let s = "She sells sea shells" in
Str.global_replace (Str.regexp "se[^ \\t\\n]*") "X" s
csharp
using System.Text.RegularExpressions;

class SolutionXX
{
static void Main()
{
string text = "She sells sea shells";
string result = Regex.Replace(text, @"se\w+", "X");
}
}
php
echo preg_replace('/se\w+/', 'X', 'She sells sea shells');
clojure
(.replaceAll (re-matcher #"se\w+" "She sells sea shells") "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+)\}/.
ruby
"The {Quick} Brown {Fox}".gsub(/\{(\w+)\}/) {|s| s[1..-2].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);
perl
$text = "The {Quick} Brown {Fox}";
$text =~ s/\{(\w+)\}/reverse($1)/ge;
groovy
replaced = "The {Quick} Brown {Fox}".replaceAll(/\{(\w+)\}/, { full, word -> word.reverse() } )
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)
python
transformed = re.sub(r'\{(\w+)\}',
lambda match: match.group(1)[::-1],
'The {Quick} Brown {Fox}')
cpp
String^ Replaced = (gcnew Regex("{(\\w+)}"))->Replace("The {Quick} Brown {Fox}", gcnew MatchEvaluator(&RegRep::RepGroup));
String^ Replaced = Regex::Replace("The {Quick} Brown {Fox}", "{(\\w+)}", gcnew MatchEvaluator(&RegRep::RepGroup));
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)
erlang
% Erlang regular expressions lack both group capture and backreferences, thus this problem is not directly
% solvable. Presented solution is close, but not on-spec

String = "The {Quick} Brown {Fox}",
{match, FieldList} = regexp:matches(String, "\{([A-Za-z0-9_]+)\}"),

NewString = lists:foldl(fun ({Start, Length}, S) -> replstr(S, lists:reverse(string:substr(S, Start, Length)), Start) end, String, FieldList),
ocaml
let s = "The {Quick} Brown {Fox}" in
let r = Str.regexp "{\\([^ \\t\\n]*\\)}" in
Str.global_substitute r (fun m -> string_rev (Str.matched_group 1 m)) s
php
// We have to use the e-modifier
preg_replace("/\{(\w+)\}/e", "''.strrev('\\1').''", "The {Quick} Brown {Fox}");
// We could use a Closure (callback function)
preg_replace_callback("/\{(\w+)\}/", function($m) { return strrev($m[1]); }, "The {Quick} Brown {Fox}");
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))))
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