Pattern matching on the beginning of a string in f#

Jeff picture Jeff · Sep 16, 2010 · Viewed 15.1k times · Source

I am trying to match the beginning of strings in f#. Not sure if I have to treat them as a list of characters or what. Any suggestions would be appreciated.

Here is a psuedo code version of what I am trying to do

let text = "The brown fox.."

match text with
| "The"::_ -> true
| "If"::_ -> true
| _ -> false

So, I want to look at the beginning of the string and match. Note I am not matching on a list of strings just wrote the above as an idea of the essence of what I am trying to do.

Answer

Brian picture Brian · Sep 16, 2010

Parameterized active patterns to the rescue!

let (|Prefix|_|) (p:string) (s:string) =
    if s.StartsWith(p) then
        Some(s.Substring(p.Length))
    else
        None

match "Hello world" with
| Prefix "The" rest -> printfn "Started with 'The', rest is %s" rest
| Prefix "Hello" rest -> printfn "Started with 'Hello', rest is %s" rest
| _ -> printfn "neither"