我是编程新手,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#:检测正则表达式模式中的错误
发布评论