F# 模式匹配数字字符串

F# 模式匹配数字字符串,f#,pattern-matching,F#,Pattern Matching,我有一个模式与其参数匹配的函数,它是一个字符串: let processLexime lexime match lexime with | "abc" -> ... | "bar" -> ... | "cat" -> ... | _ -> ... 这正如预期的那样有效。然而,我现在试图通过表达“匹配一个只包含以下字符的字符串”来扩展它。在我的具体示例中,我希望匹配任何只包含数字的内容 我的问题是,我如何用F#来表达这一点?

我有一个模式与其参数匹配的函数,它是一个
字符串

let processLexime lexime
    match lexime with
    | "abc" -> ...
    | "bar" -> ...
    | "cat" -> ...
    | _     -> ...
这正如预期的那样有效。然而,我现在试图通过表达“匹配一个只包含以下字符的
字符串”
来扩展它。在我的具体示例中,我希望匹配任何只包含数字的内容


我的问题是,我如何用F#来表达这一点?我更愿意在没有任何库的情况下这样做,例如
FParsec
,因为我这样做主要是为了学习。

一种方法是使用活动模式

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

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

您可以使用活动模式:


我将使用正则表达式与活动模式相结合。使用正则表达式,您可以轻松地将数字与
\d
进行匹配,而活动模式使
匹配中的语法更加优美

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 
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 
only w
only w and s
only digis
wrong