Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching on the beginning of a string in f#

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.

like image 503
Jeff Avatar asked Sep 15 '10 23:09

Jeff


People also ask

What is pattern matching in F#?

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”.

What is matching string pattern?

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.

How do I find a specific pattern in a string?

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.

Which keyword is used for string pattern matching?

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.


1 Answers

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" 
like image 139
Brian Avatar answered Sep 23 '22 22:09

Brian