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

如何解决F#映射正则表达式与活动模式匹配

| 我发现这篇关于将活动模式与正则表达式结合使用的有用文章: 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
它将使您知道是否至少找到一个网址以及该网址是什么(如果我正确理解了代码段) 然后,Joel在评论部分中建议了此修改:   替代方案,因为给定的组   或未必成功:
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.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\",1)]
这基本上是我要寻找的结果,但是我正在尝试学习执行此操作的功能方法,我认为其中应该包括活动模式。如果这比我的第一次尝试有意义,请随意尝试“功能化”。 提前致谢, 鲍勃     

解决方法

有趣的东西,我认为您在这里探索的一切都是有效的。正则表达式匹配的(部分)活动模式确实非常有效。尤其是当您有一个字符串要与多个替代情况匹配时。我建议使用更复杂的regex活动模式的唯一目的是给它们提供更具描述性的名称,可能会建立具有不同用途的不同regex活动模式的集合。 至于您的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)我们正在测试一个与多个组匹配的正则表达式。对于这些情况,我使用以下两个活动模式,它们比您显示的第一个“ 9”活动模式要通用一些(我不会在比赛中丢弃第一个组,而是返回Group对象的列表,而不仅仅是它们的值-一种用于静态正则表达式模式的已编译正则表达式选项,一种用于动态正则表达式模式的解释后的正则表达式选项)。由于.NET正则表达式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
还请注意,这些活动模式如何将null视为不匹配项,而不是引发异常。 好的,假设我们要解析名称。我们有以下要求: 必须有名字和姓氏 可能有中间名 首先,可选的中间名和姓氏以单个空格分隔 名称的每个部分都可以包含至少一个或多个字母或数字的任意组合 输入可能格式错误 首先,我们将定义以下记录:
type Name = {First:string; Middle:option<string>; Last:string}
然后,我们可以在用于解析名称的函数中非常有效地使用regex活动模式:
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
注意,这里获得的主要优点之一(通常是模式匹配的情况)是,我们能够同时测试输入是否与regex模式匹配,如果能够匹配,则分解返回的组列表。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-