I have a string that I know will match one (and only one) of three regexes. I want to try each regex in turn until a match is found. For two of the regexes it is sufficient to know that there is a match. The third regex has a capture group and returns an integer. I have an active pattern for regex:
let (|Regex|_|) pattern input =
let m = Regex.Match(input, pattern)
if m.Success then Some(List.tail [ for g in m.Groups -> g.Value ])
else None
I’m new to F# and struggling for an idiomatic way to do this. I don’t really want to make a convoluted if-then-else expression, Any help would be really appreciated.
Thanks
With your handy function all you need to do is use match with your 3 patterns:
let regex1 = "^[1234]+$"
let regex2 = "^[abcd]+$"
let regex3 = "^ab([123])$"
let testText v =
match v with
| Regex regex1 _ -> "matched 1!"
| Regex regex2 _ -> "matched 2!"
| Regex regex3 [ d ] -> sprintf "matched 3 = %d" (int d)
| _ -> "no match"
testText "231" |> printfn "%s" // matched 1!
testText "abd" |> printfn "%s" // matched 2!
testText "ab2" |> printfn "%s" // matched 3 = 2
testText "ab5" |> printfn "%s" // no match
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With