代码之家  ›  专栏  ›  技术社区  ›  Jeff

f中字符串开头的模式匹配#

  •  53
  • Jeff  · 技术社区  · 14 年前

    我正在尝试匹配f#中字符串的开头。不知道我是不是要把它们当作一个字符列表。如有任何建议,将不胜感激。

    这是一个psuedo代码版本的我正在尝试做的

    let text = "The brown fox.."
    
    match text with
    | "The"::_ -> true
    | "If"::_ -> true
    | _ -> false
    

    所以,我想看看字符串的开头并匹配。请注意,我不是在一个字符串列表上匹配刚刚写的,作为我试图做的本质的想法上面。

    3 回复  |  直到 14 年前
        1
  •  100
  •   Brian    14 年前

    active patterns 为救援干杯!

    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"
    
        2
  •  18
  •   trgt    11 年前

    您也可以在图案上使用防护装置:

    match text with
    | txt when txt.StartsWith("The") -> true
    | txt when txt.StartsWith("If") -> true
    | _ -> false
    
        3
  •  13
  •   elmattic    14 年前

    let text = "The brown fox.." |> Seq.toList
    

    然后可以使用匹配表达式,但必须为每个字母使用字符(列表中元素的类型):

    match text with
    | 'T'::'h'::'e'::_ -> true
    | 'I'::'f'::_ -> true
    | _ -> false
    

    here (转到本页末尾)。