简体   繁体   中英

What is the easiest way in C# to validate if a regular expression is well formed?

Is there any simple way in C# to test if a regular expression is a regular expression? In other words, I would like to check if a user-provided regex pattern is malformed or not. This is purely a syntax test and not what the regex is supposed to achieve/test. Thanks

您可以尝试将其传递给Regex构造函数并捕获可能的ArgumentException ,如果参数是格式错误的正则表达式,则抛出该ArgumentException

Here's an example from C# Online .NET that uses exceptions:

EDIT:

Removed the code to respect copyright owners, just in case. Simply click on the above link to see it.

I have to say, this doesn't sound good. The extremely small subset of computer users that would be capable of correctly entering a regex should probably also be trusted to interpret the exception message correctly. Trying to validate their entry and getting it wrong would be sufficient grounds for them to get pretty flipping mad and uninstall your program.

If experienced programmers are not actually your target customer, be sure to avoid regex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM