Can I test if a regex is valid in C# without throwing exception

后端 未结 8 1878
挽巷
挽巷 2020-12-03 13:19

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 expression

8条回答
  •  悲哀的现实
    2020-12-03 13:41

    Not without a lot of work. Regex parsing can be pretty involved, and there's nothing public in the Framework to validate an expression.

    System.Text.RegularExpressions.RegexNode.ScanRegex() looks to be the main function responsible for parsing an expression, but it's internal (and throws exceptions for any invalid syntax anyway). So you'd be required to reimplement the parse functionality - which would undoubtedly fail on edge cases or Framework updates.

    I think just catching the ArgumentException is as good an idea as you're likely to have in this situation.

提交回复
热议问题