我可以测试一个正则表达式是在C#中有效的没有抛出异常 [英] Can I test if a regex is valid in C# without throwing exception

查看:205
本文介绍了我可以测试一个正则表达式是在C#中有效的没有抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我允许用户输入一个普通的前pression匹配的IP地址,在一个相关的系统做一个IP过滤。我想验证如果输入的常规前pressions是因为很多userse会搞乱运算的有效,有良好的愿望,但。

I allow users to enter a regular expression to match IP addresses, for doing an IP filtration in a related system. I would like to validate if the entered regular expressions are valid as a lot of userse will mess op, with good intentions though.

我当然可以做一个Regex.IsMatch()一个try / catch里面,看看它是否打击了这种方式,但是否有这样做的任何更聪明的方法?速度不是一个问题,因为这样,我只是preFER避免无故抛出异常。

I can of course do a Regex.IsMatch() inside a try/catch and see if it blows up that way, but are there any smarter ways of doing it? Speed is not an issue as such, I just prefer to avoid throwing exceptions for no reason.

推荐答案

只要你赶上非常特殊的例外,只是做了个try / catch。

As long as you catch very specific exceptions, just do the try/catch.

例外不是邪恶的。

这篇关于我可以测试一个正则表达式是在C#中有效的没有抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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