How to check if an input contains a valid .Net regular expression?

I am creating an application that saves named regular expressions to a database. Looks like that:

Regex form

I am using Asp.Net forms. How can I check the entered regular expression? He would like the user to know that the regular expression entered is not a valid .Net regular expression.

The field should reject values ​​such as:

^Wrong(R[g[x)]]$ Invalid\Q&\A 
+4
source share
2 answers

Extract the new Regex class from it. If it throws an exception, then it is invalid.

 try{ new Regex(expression) } catch(ArgumentException ex) { // invalid regex } // valid regex 

I know. Using exceptions for code logic is wrong. But this seems to be only a solution.

+6
source

Something like this is possible:

 public static class RegexUtils { public static bool TryParse (string possibleRegex, out Regex regex) { regex = null; try { regex = new Regex(possibleRegex); return true; } catch (ArgumentException ae) { return false; } } } 
+2
source

Source: https://habr.com/ru/post/1442286/


All Articles