F#中使用正则表达式进行模式匹配

时间:2015-09-18 08:27:57

标签: regex f#

如何从任何给定字符串中找到“From:Sent:Received:”模式。如果给定模式存在于字符串中,则将子字符串取出到第一个模式并忽略其余字符串。是否有任何正则表达式来实现相同的目标? 注意:From:Sent:和received:。之间可能存在文本。

1 个答案:

答案 0 :(得分:4)

使用partial active pattern这可能看起来像

open System.Text.RegularExpressions

let (|UpToFromSentReceived|_|) candidate =
    let pattern = Regex("(.*?)From:.*Sent:.*Received:")
    let matches = pattern.Match candidate
    if matches.Success then matches.Groups.[1].Value.Trim() |> Some else None
然后可以使用

let test = function
    | UpToFromSentReceived prefix -> printfn "%s" prefix
    | s -> printfn "No match for '%s'" s

// Arbitrary prefix
test "Arbitrary prefix From: Sent: Received:"

// No match for 'Arbitrary prefix From: Sent: sorry ;-P'
test "Arbitrary prefix From: Sent: sorry ;-P"

// Foo Bar
test "Foo Bar From: arbitrary Sent: interspersed Received: text"

// First Foo Bar
test "First Foo Bar From: arbitrary Sent: interspersed Received: text Second Foo Bar From: arbitrary Sent: interspersed Received: text"

根据您的要求,您可能希望省略.Trim()