... | "b...">

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.

+5
source share
3 answers

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 
+3
source

One way is an active template.

 let (|Digits|_|) (s:string) = s.ToCharArray() |> Array.forall (fun c -> System.Char.IsDigit(c)) |> function |true -> Some(s) |false -> None 

then you can do

 match "1" with |Digits(t) -> printf "matched" 
+2
source

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 
+1
source

Source: https://habr.com/ru/post/1241333/


All Articles