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

时间:2010-09-15 23:21:56

标签: f# pattern-matching

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

这是我正在尝试做的伪代码版本

let text = "The brown fox.."

match text with
| "The"::_ -> true
| "If"::_ -> true
| _ -> false

所以,我想看一下字符串和匹配的开头。注意我没有匹配一个字符串列表只是写了上面的内容作为我想要做的事情的本质的想法。

3 个答案:

答案 0 :(得分:89)

参与化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"

答案 1 :(得分:16)

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

match text with
| txt when txt.StartsWith("The") -> true
| txt when txt.StartsWith("If") -> true
| _ -> false

答案 2 :(得分:12)

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

只需使用以下符号转换字符串:

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

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

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

正如Brian建议参数化活动模式更好,有一些有用的模式here(在页面末尾)。

相关问题