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

Jef*_*eff 56 f# pattern-matching

我想在f#中匹配字符串的开头.不确定我是否必须将它们视为字符列表或什么.任何建议,将不胜感激.

这是我想要做的psuedo代码版本

let text = "The brown fox.."

match text with
| "The"::_ -> true
| "If"::_ -> true
| _ -> false
Run Code Online (Sandbox Code Playgroud)

所以,我想看一下字符串和匹配的开头.注意我不是在字符串列表上匹配只是写了上面作为我想要做的本质的想法.

Bri*_*ian 94

参数化的活动模式来拯救!

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"
Run Code Online (Sandbox Code Playgroud)


小智 16

你也可以在模式上使用一个守卫:

match text with
| txt when txt.StartsWith("The") -> true
| txt when txt.StartsWith("If") -> true
| _ -> false
Run Code Online (Sandbox Code Playgroud)


Str*_*ger 12

是的,如果要使用匹配表达式,则必须将它们视为字符列表.

只需转换字符串:

let text = "The brown fox.." |> Seq.toList
Run Code Online (Sandbox Code Playgroud)

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

match text with
| 'T'::'h'::'e'::_ -> true
| 'I'::'f'::_ -> true
| _ -> false
Run Code Online (Sandbox Code Playgroud)

布赖恩建议参数活动模式是好得多,有没有一些有用的模式在这里(转到页的结尾).

  • 因为字符串已经是`char seq`,所以你可以使用`Seq.toList`. (4认同)