F#:检测正则表达式模式中的错误

编程入门 行业动态 更新时间:2024-10-23 15:24:10
本文介绍了F#:检测正则表达式模式中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是编程新手,F#是我的第一门.NET语言.

I am new to programming and F# is my first .NET language.

作为一个初学者的项目,我想编写一个应用程序,要求用户输入一个正则表达式模式,然后标记任何错误.

As a beginner's project, I would like to write an application asking the user to enter a regex pattern and then flagging any errors.

我已经查看了MSDN上的Regex API,但似乎没有任何方法可以自动检测到regex模式中的任何错误.会不会有更多经验丰富的程序员与我分享他们如何实现这一目标?

I have looked through the Regex API on MSDN but there doesn't seem to be any methods that would automatically detect any errors in regex patterns. Will more experienced programmers kindly share with me how they would go about accomplishing this?

预先感谢您的帮助.

推荐答案

如果需要检查正则表达式是否编译,只需使用尝试块.如果需要检查正则表达式模式是否与您的输入字符串匹配,请使用IsMatch()或.Success.够了.

If you need to check if a regex compiles or not, simply use try-with block. If you need to check if a regex pattern matches your input string, use IsMatch() or .Success. That is quite enough.

一个示例,该代码取自另一篇SO文章,但正则表达式模式中有一个错误,其中我将(http:\/\/\S+)替换为(http:\/\/\S+:

An example with code taken from another SO post, but with an error in regex pattern where I replaced (http:\/\/\S+) with (http:\/\/\S+:

try let testString = "www.bob www.b www.bob www.bill" 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)) with | :? System.Exception as ex -> printfn "Exception! %s " (ex.Message); None

可以在此处或此处.

更多推荐

F#:检测正则表达式模式中的错误

本文发布于:2023-11-17 03:11:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608607.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   模式   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!