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

发布于 2024-09-19 07:42:46 字数 276 浏览 5 评论 0原文

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

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

let text = "The brown fox.."

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

所以,我想查看字符串的开头并进行匹配。请注意,我没有匹配字符串列表,只是将上面的内容写为我想要做的事情的本质的想法。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

蹲在坟头点根烟 2024-09-26 07:42:46

参数化活动模式来救援!

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"

Parameterized active patterns to the rescue!

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"
岁月静好 2024-09-26 07:42:46

您还可以在模式上使用防护:

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

You could also use a guard on the pattern:

match text with
| txt when txt.StartsWith("The") -> true
| txt when txt.StartsWith("If") -> true
| _ -> false
预谋 2024-09-26 07:42:46

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

只需将字符串转换为:

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

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

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

正如 Brian 建议的那样,参数化活动模式要好得多,有一些有用的模式 此处(转到页面末尾)。

Yes you have to treat them as a list of characters if you want to use a match expression.

Simply transform the string with:

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

Then you can use a match expression but you will have to use chars (the type of elements in the list) for each letter:

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

As Brian suggest Parameterized Active Patterns are much nicer, there a some useful patterns here (go the end of the page).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文