KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I found this useful article on using Active Patterns with Regular Expressions: http://www.markhneedham.com/blog/2009/05/10/f-regular-expressionsactive-patterns/ The original code snippet used in the article was this: open System.Text.RegularExpressions let (|Match|_|) pattern input = let m = Regex.Match(input, pattern) in if m.Success then Some (List.tl [ for g in m.Groups -> g.Value ]) else None let ContainsUrl value = match value with | Match "(http:\/\/\S+)" result -> Some(result.Head) | _ -> None Which would let you know if at least one url was found and what that url was (if I understood the snippet correctly) Then in the comment section Joel suggested this modification: Alternative, since a given group may or may not be a successful match: List.tail [ for g in m.Groups -> if g.Success then Some g.Value else None ] Or maybe you give labels to your groups and you want to access them by name: (re.GetGroupNames() |> Seq.map (fun n -> (n, m.Groups.[n])) |> Seq.filter (fun (n, g) -> g.Success) |> Seq.map (fun (n, g) -> (n, g.Value)) |> Map.ofSeq) After trying to combine all of this I came up with the following code: let testString = "http://www.bob.com http://www.b.com http://www.bob.com http://www.bill.com" let (|Match|_|) pattern input = let re = new Regex(pattern) let m = re.Match(input) in if m.Success then Some ((re.GetGroupNames() |> Seq.map (fun n -> (n, m.Groups.[n])) |> Seq.filter (fun (n, g) -> g.Success) |> Seq.map (fun (n, g) -> (n, g.Value)) |> Map.ofS
Tags (comma-separated)
Save Edits
Cancel