View Subcategory

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
csharp
if(System.Text.RegularExpressions.Regex.IsMatch("abc 123 @#$",@"\d+")){
Console.WriteLine("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.
cpp
if (Regex::IsMatch("abc 123 @#$", "\\d+")) Console::WriteLine("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+)/
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;});
}
}
erlang
solve(S) ->
R = "\\((\\w+?)\\):(\\d+)",
{match, M} = re:run(S,R, [global, {capture, all_but_first, list}]),
[ A++N || [A, N] <- M].
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();
}