Regular Expressions in F#
Our first program demonstrates how to work with regular expressions in F#. Here’s the full source code:
open System
open System.Text.RegularExpressions
let main() =
// This tests whether a pattern matches a string.
let match1 = Regex.IsMatch("peach", "p([a-z]+)ch")
printfn "%b" match1
// For other regexp tasks, you'll need to create a Regex object.
let r = Regex("p([a-z]+)ch")
// Many methods are available on these objects. Here's a match test like we saw earlier.
printfn "%b" (r.IsMatch("peach"))
// This finds the match for the regexp.
printfn "%s" (r.Match("peach punch").Value)
// This also finds the first match but returns the start and end indexes for the match.
let m = r.Match("peach punch")
printfn "idx: [%d %d]" m.Index (m.Index + m.Length)
// The Groups property provides information about both the whole-pattern matches
// and the submatches within those matches.
let groups = r.Match("peach punch").Groups
printfn "%A" [for g in groups -> g.Value]
// Similarly, we can get information about the indexes of matches and submatches.
printfn "%A" [for g in groups -> [g.Index; g.Index + g.Length]]
// The Matches method finds all matches in the input.
let matches = r.Matches("peach punch pinch")
printfn "%A" [for m in matches -> m.Value]
// We can limit the number of matches.
let limitedMatches = r.Matches("peach punch pinch") |> Seq.take 2
printfn "%A" [for m in limitedMatches -> m.Value]
// Our examples above had string arguments. We can also provide byte arrays.
let bytes = Text.Encoding.ASCII.GetBytes("peach")
printfn "%b" (r.IsMatch(Text.Encoding.ASCII.GetString(bytes)))
// The regexp package can also be used to replace subsets of strings with other values.
printfn "%s" (r.Replace("a peach", "<fruit>"))
// The Replace method allows you to transform matched text with a given function.
let upperReplace (m: Match) = m.Value.ToUpper()
let result = r.Replace("a peach", MatchEvaluator(upperReplace))
printfn "%s" result
main()
To run the program, save it as RegularExpressions.fs
and use the F# compiler (fsc
) to compile it, then run the resulting executable:
$ fsharpc RegularExpressions.fs
$ mono RegularExpressions.exe
true
true
peach
idx: [0 5]
["peach"; "ea"]
[[0; 5]; [1; 3]]
["peach"; "punch"; "pinch"]
["peach"; "punch"]
true
a <fruit>
a PEACH
This example demonstrates how to use regular expressions in F#. The System.Text.RegularExpressions
namespace provides functionality similar to Go’s regexp
package.
Note that F# uses the .NET regular expression engine, which has some differences in syntax and features compared to Go’s regular expressions. Always refer to the F# and .NET documentation for the most accurate and up-to-date information on regular expressions in F#.
For a complete reference on F# and .NET regular expressions, check the System.Text.RegularExpressions
namespace documentation.