21

我发现这篇关于使用正则表达式的活动模式的有用文章:http: //www.markhneedham.com/blog/2009/05/10/f-regular-expressionsactive-patterns/

文章中使用的原始代码片段是这样的:

open System.Text.RegularExpressions

let (|Match|_|) pattern input =
    let m = Regex.Match(input, pattern) in
    if m.Success then Some (List.tl [ for g in m.Groups -> g.Value ]) else None

let ContainsUrl value = 
    match value with
        | Match "(http:\/\/\S+)" result -> Some(result.Head)
        | _ -> None

这会让您知道是否找到了至少一个 url 以及该 url 是什么(如果我正确理解了该片段)

然后在评论部分乔尔提出了这个修改:

另一种选择,因为给定的组可能是也可能不是成功的匹配:

List.tail [ for g in m.Groups -> if g.Success then Some g.Value else None ]

或者,也许您为您的组提供标签,并且您想按名称访问它们:

(re.GetGroupNames()
 |> Seq.map (fun n -> (n, m.Groups.[n]))
 |> Seq.filter (fun (n, g) -> g.Success)
 |> Seq.map (fun (n, g) -> (n, g.Value))
 |> Map.ofSeq)

在尝试结合所有这些之后,我想出了以下代码:

let testString = "http://www.bob.com http://www.b.com http://www.bob.com http://www.bill.com"

let (|Match|_|) pattern input =
    let re = new Regex(pattern)
    let m = re.Match(input) in
    if m.Success then Some ((re.GetGroupNames()
                                |> Seq.map (fun n -> (n, m.Groups.[n]))
                                |> Seq.filter (fun (n, g) -> g.Success)
                                |> Seq.map (fun (n, g) -> (n, g.Value))
                                |> Map.ofSeq)) else None

let GroupMatches stringToSearch = 
    match stringToSearch with
        | Match "(http:\/\/\S+)" result -> printfn "%A" result
        | _ -> ()


GroupMatches testString;;

当我在交互式会话中运行代码时,输​​出如下:

map [("0", "http://www.bob.com"); ("1", "http://www.bob.com")]

我试图达到的结果看起来像这样:

map [("http://www.bob.com", 2); ("http://www.b.com", 1); ("http://www.bill.com", 1);]

基本上是找到的每个唯一匹配的映射,然后是在文本中找到特定匹配字符串的次数的计数。

如果您认为我在这里走错了路,请随时提出完全不同的方法。我对活动模式和正则表达式都有点陌生,所以我什至不知道从哪里开始尝试解决这个问题。

我也想出了这个,这基本上就是我在 C# 中翻译成 F# 时所做的。

let testString = "http://www.bob.com http://www.b.com http://www.bob.com http://www.bill.com"

let matches =
    let matchDictionary = new Dictionary<string,int>()
    for mtch in (Regex.Matches(testString, "(http:\/\/\S+)")) do
        for m in mtch.Captures do
            if(matchDictionary.ContainsKey(m.Value)) then
                matchDictionary.Item(m.Value) <- matchDictionary.Item(m.Value) + 1
            else
                matchDictionary.Add(m.Value, 1)
    matchDictionary

运行时返回:

val matches : Dictionary = dict [("http://www.bob.com", 2); ("http://www.b.com", 1); ("http://www.bill.com", 1)]

这基本上是我正在寻找的结果,但我正在尝试学习执行此操作的功能方式,我认为这应该包括活动模式。如果它比我的第一次尝试更有意义,请随意尝试“功能化”它。

提前致谢,

鲍勃

4

1 回答 1

26

有趣的东西,我认为你在这里探索的一切都是有效的。正则表达式匹配的(部分)活动模式确实非常有效。尤其是当您有一个要匹配多个替代情况的字符串时。对于更复杂的正则表达式活动模式,我建议的唯一一件事是你给它们更多的描述性名称,可能会建立一个具有不同目的的不同正则表达式活动模式的集合。

至于您的 C# 到 F# 示例,您可以在没有活动模式的情况下使用功能解决方案,例如

let testString = "http://www.bob.com http://www.b.com http://www.bob.com http://www.bill.com"

let matches input =
    Regex.Matches(input, "(http:\/\/\S+)") 
    |> Seq.cast<Match>
    |> Seq.groupBy (fun m -> m.Value)
    |> Seq.map (fun (value, groups) -> value, (groups |> Seq.length))

//FSI output:
> matches testString;;
val it : seq<string * int> =
  seq
    [("http://www.bob.com", 2); ("http://www.b.com", 1);
     ("http://www.bill.com", 1)]

更新

这个特定示例在没有活动模式的情况下工作正常的原因是因为 1)您只测试一个模式,2)您正在动态处理匹配项。

对于活动模式的真实示例,让我们考虑以下情况:1)我们正在测试多个正则表达式,2)我们正在测试一个正则表达式与多个组的匹配。对于这些场景,我使用以下两个活动模式,它们比Match您展示的第一个活动模式更通用(我没有丢弃匹配中的第一个组,我返回 Group 对象的列表,而不仅仅是它们的值-- 一种使用编译的正则表达式选项用于静态正则表达式模式,一种使用解释的正则表达式选项用于动态正则表达式模式)。因为 .NET 正则表达式 API 的功能如此丰富,所以您从活动模式返回的内容实际上取决于您认为有用的内容。但是返回 a listof something很好,因为这样您就可以在该列表上进行模式匹配。

let (|InterpretedMatch|_|) pattern input =
    if input = null then None
    else
        let m = Regex.Match(input, pattern)
        if m.Success then Some [for x in m.Groups -> x]
        else None

///Match the pattern using a cached compiled Regex
let (|CompiledMatch|_|) pattern input =
    if input = null then None
    else
        let m = Regex.Match(input, pattern, RegexOptions.Compiled)
        if m.Success then Some [for x in m.Groups -> x]
        else None

还要注意这些活动模式如何将 null 视为不匹配,而不是抛出异常。

好的,假设我们要解析名称。我们有以下要求:

  1. 必须有名字和姓氏
  2. 可能有中间名
  3. 首先,可选的中间名和姓氏按顺序用一个空格分隔
  4. 名称的每一部分可以由至少一个或多个字母或数字的任意组合组成
  5. 输入可能格式错误

首先,我们将定义以下记录:

type Name = {First:string; Middle:option<string>; Last:string}

然后我们可以在解析名称的函数中非常有效地使用我们的正则表达式活动模式:

let parseName name =
    match name with
    | CompiledMatch @"^(\w+) (\w+) (\w+)$" [_; first; middle; last] ->
        Some({First=first.Value; Middle=Some(middle.Value); Last=last.Value})
    | CompiledMatch @"^(\w+) (\w+)$" [_; first; last] ->
        Some({First=first.Value; Middle=None; Last=last.Value})
    | _ -> 
        None

请注意,我们在这里获得的关键优势之一(通常是模式匹配的情况)是我们能够同时测试输入是否与正则表达式模式匹配,如果匹配,则分解返回的组列表。

于 2011-04-16T03:57:22.077 回答