F#:检测正则表达式模式中的错误 [英] F#: Detecting errors in regex patterns

查看:73
本文介绍了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?

预先感谢您的帮助.

推荐答案

如果需要检查正则表达式是否编译,只需使用

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 = "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))
with
    | :? System.Exception as ex -> printfn "Exception! %s " (ex.Message); None    

可以在此处 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆