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.
Advertisements. Pattern matching allows you to “compare data with a logical structure or structures, decompose data into constituent parts, or extract information from data in various ways”.
A string enclosed within double quotes ('"') is used exclusively for pattern matching (patterns are a simplified form of regular expressions - used in most UNIX commands for string matching). Patterns are internally converted to equivalent regular expressions before matching.
To check if a String matches a Pattern one should perform the following steps: Compile a String regular expression to a Pattern, using compile(String regex) API method of Pattern. Use matcher(CharSequence input) API method of Pattern to create a Matcher that will match the given String input against this pattern.
In SQL, the LIKE keyword is used to search for patterns. Pattern matching employs wildcard characters to match different combinations of characters. The LIKE keyword indicates that the following character string is a matching pattern. LIKE is used with character data.
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"
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