开发者

Validating regular expression without catching exception?

开发者 https://www.devze.com 2022-12-12 12:19 出处:网络
In a .NET application (written in C#) I have a UI with a list and a text box used to enter a filter string to filter what is displayed in the list. I refresh the filter as the user types.

In a .NET application (written in C#) I have a UI with a list and a text box used to enter a filter string to filter what is displayed in the list. I refresh the filter as the user types.

I now want to allow use of regular expressions in the filter string, which poses a problem. As the user types the expre开发者_JS百科ssion it may be invalid, for instance between the time that an opening bracket is typed and the time that the closing bracket is typed. Newing up a Regex with an invalid expression throws an exception and I want to prevent this. One way is to catch the exception but I was wondering if there is some way to check that the expression is a valid regular expression without actually trying to new up a Regex with it.


Just catch the exception. Given that this will be happening in response to user input there will be absolutely no significant performance penalty.


I would have a special start character that the user types to indicate they are starting a regex, at that point you can stop the live processing of the typed text until a special ending character is typed, at which point you new up and apply the regex.

0

精彩评论

暂无评论...
验证码 换一张
取 消