ok I have the following strings
"^[a-z]*$"
and
"a-z"
now what I want with those two strings is to check if they are valid Regular Expressions strings in VB.NET. I really have no idea how can I make it... but I tried something below
Try
Dim regex As Regex = New Regex("a-z")
Return "valid regex"
Catch ex As Exception
Return "not valid regex"
End Try
but my solution above seems not really good. Is there much better solution?
new String(). matches(regEx) can be directly be used with try-catch to identify if regEx is valid. While this does accomplish the end result, Pattern. compile(regEx) is simpler (and is exactly what will end up happening anyway) and doesn't have any additional complexity.
For examples, \+ matches "+" ; \[ matches "[" ; and \. matches "." . Regex also recognizes common escape sequences such as \n for newline, \t for tab, \r for carriage-return, \nnn for a up to 3-digit octal number, \xhh for a two-digit hex code, \uhhhh for a 4-digit Unicode, \uhhhhhhhh for a 8-digit Unicode.
IsMatch(String, String, RegexOptions) Indicates whether the specified regular expression finds a match in the specified input string, using the specified matching options.
A regular expression is a pattern that could be matched against an input text. The . Net framework provides a regular expression engine that allows such matching. A pattern consists of one or more character literals, operators, or constructs.
No, there is no other solution (you could of course reimplement the regex parser, but that would be an error-prone hell of work).
I would prefer catching the specific ArgumentException
that the Regex
constructor throws if the regex is invalid other than just Exception
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With