View Category

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
fsharp
if (Regex.IsMatch("Hello", "[A-Z][a-z]+")) then printfn "ok"

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
fsharp
let regmatch = (Regex.Match("one two three", "one (.*) three"))
if regmatch.Success then (printfn "%s" (regmatch.Groups.[1].Captures.[0].ToString()))

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
fsharp
if (Regex.IsMatch("abc 123 @#$", "\\d+")) then printfn "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+)/
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

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 "*"
fsharp
let replaced = ((new Regex("e")).Replace("Red Green Blue", "*", 1))
printfn "%s" replaced

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"
fsharp
let replaced = ((new Regex("se\\w+")).Replace("She sells sea shells", "X"))
printfn "%s" replaced

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+)\}/.
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)