F#使用活动模式映射正则表达式匹配

Bea*_*ker 19 regex f# f#-interactive active-pattern

我发现这篇关于使用带有正则表达式的活动模式的有用文章: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
Run Code Online (Sandbox Code Playgroud)

如果找到至少一个网址以及该网址是什么(如果我正确理解了该网址片段),会告诉您

然后在评论部分Joel建议这个修改:

替代方案,因为给定的组可能是也可能不是成功匹配:

List.tail [ for g in m.Groups -> if g.Success then Some g.Value else None ]
Run Code Online (Sandbox Code Playgroud)

或者,您可以为组添加标签,并希望按名称访问它们:

(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)
Run Code Online (Sandbox Code Playgroud)

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

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;;
Run Code Online (Sandbox Code Playgroud)

当我在交互式会话中运行我的代码时,这是输出:

map [("0", "http://www.bob.com"); ("1", "http://www.bob.com")]
Run Code Online (Sandbox Code Playgroud)

我想要实现的结果看起来像这样:

map [("http://www.bob.com", 2); ("http://www.b.com", 1); ("http://www.bill.com", 1);]
Run Code Online (Sandbox Code Playgroud)

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

如果您认为我走错了路,请随意提出一个完全不同的方法.我对Active Patterns和Regular Expressions都不熟悉,所以我不知道在哪里开始尝试解决这个问题.

我也想出了这个,这基本上就是我在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
Run Code Online (Sandbox Code Playgroud)

运行时返回此信息:

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

这基本上是我正在寻找的结果,但我正在尝试学习这种功能的方法,我认为应该包括活动模式.如果它比我的第一次尝试更有意义,请随意尝试"功能化".

提前致谢,

短发

Ste*_*sen 24

有趣的是,我认为你在这里探索的一切都是有效的.(部分)正则表达式匹配的活动模式确实非常有效.特别是当你有一个字符串,你想要匹配多个替代案例.对于更复杂的正则表达式活动模式,我唯一建议的是,为它们提供更具描述性的名称,可能构建具有不同目的的不同正则表达式活动模式的集合.

至于你的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)]
Run Code Online (Sandbox Code Playgroud)

更新

为什么这个例子正常工作不主动模式的原因是因为:1)您只测试一个模式,2)要动态处理比赛.

对于活动模式的真实世界示例,让我们考虑一种情况:1)我们正在测试多个正则表达式,2)我们正在测试一个与多个组的正则表达式匹配.对于这些场景,我使用以下两种活动模式,这些模式比Match您显示的第一个活动模式更通用(我不会丢弃匹配中的第一个组,并返回组对象的列表,而不仅仅是它们的值 - 一个使用已编译的正则表达式选项用于静态正则表达式模式,一个使用解释的正则表达式选项用于动态正则表达式模式).因为.NET regex API是如此功能填充,所以从活动模式返回的内容实际上取决于您认为有用的内容.但返回list东西是好的,因为这样你可以在此列模式匹配.

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
Run Code Online (Sandbox Code Playgroud)

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

好的,所以我们要说我们要解析名称.我们有以下要求:

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

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

type Name = {First:string; Middle:option<string>; Last:string}
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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

  • @Beaker - 当然,只是醒来,我会喝点咖啡,然后就可以了 (3认同)