Matching Number Strings
I have a function that matches a pattern that is string :
let processLexime lexime match lexime with | "abc" -> ... | "bar" -> ... | "cat" -> ... | _ -> ... This works as expected. However, I am now trying to expand this by expressing "matching a string containing only the following characters." In my specific example, I want everything containing only numbers to be matched.
My question is: how can I express this in F #? I would prefer to do this without any libraries like FParsec , since I mainly do this for training purposes.
You can use active templates: https://msdn.microsoft.com/en-us/library/dd233248.aspx
let (|Integer|_|) (str: string) = let mutable intvalue = 0 if System.Int32.TryParse(str, &intvalue) then Some(intvalue) else None let parseNumeric str = match str with | Integer i -> printfn "%d : Integer" i | _ -> printfn "%s : Not matched." str I would use regular expressions in combination with active patterns. With regular expressions, you can easily match numbers with \d , and active patterns make the syntax nice inside your match .
open System.Text.RegularExpressions let (|ParseRegex|_|) regex str = let m = Regex("^"+regex+"$").Match(str) if (m.Success) then Some true else None let Printmatch s = match s with | ParseRegex "w+" d -> printfn "only w" | ParseRegex "(w+|s+)+" d -> printfn "only w and s" | ParseRegex "\d+" d -> printfn "only digis" |_ -> printfn "wrong" [<EntryPoint>] let main argv = Printmatch "www" Printmatch "ssswwswwws" Printmatch "134554" Printmatch "1dwd3ddwwd" 0 which prints
only w only w and s only digis wrong