Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string is a valid RegEx Pattern VB.NET

Tags:

regex

vb.net

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?

like image 711
Netorica Avatar asked Jul 30 '13 07:07

Netorica


People also ask

How do you check if a regEx is valid or not?

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.

What does \+ mean in regEx?

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.

What is regEx IsMatch?

IsMatch(String, String, RegexOptions) Indicates whether the specified regular expression finds a match in the specified input string, using the specified matching options.

What is regEx in VB net?

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.


1 Answers

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.

like image 67
sloth Avatar answered Nov 15 '22 07:11

sloth