中字符串开头的模式匹配

中字符串开头的模式匹配

本文介绍了f#中字符串开头的模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试匹配f#中字符串的开头.不知道我是否必须将它们视为字符列表或其他内容.任何建议,将不胜感激.

I am trying to match the beginning of strings in f#. Not sure if I have to treat them as a list of characters or what. Any suggestions would be appreciated.

这是我要执行的操作的伪代码

Here is a psuedo code version of what I am trying to do

let text = "The brown fox.."

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

因此,我想看看字符串的开头并进行匹配.请注意,我在上面所写的字符串列表中不匹配,只是出于对我要执行的操作的本质的考虑.

So, I want to look at the beginning of the string and match. Note I am not matching on a list of strings just wrote the above as an idea of the essence of what I am trying to do.

推荐答案

参数化的处于活动状态模式以营救!

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"

这篇关于f#中字符串开头的模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 07:25