How to validate regular expression pattern?
-
Hi, I want to ask a question about Regular expressions. I want to validate the regular expression pattern if it is written correctly or not? I do not want to test a string against to a regular expression pattern but the regular expression pattern itself. Is there a way? Kind Regards
-
Hi, I want to ask a question about Regular expressions. I want to validate the regular expression pattern if it is written correctly or not? I do not want to test a string against to a regular expression pattern but the regular expression pattern itself. Is there a way? Kind Regards
Just create a new instance of the
RegEx
. If the regex is invalid, an exception is thrown (this is documented in the class constructor information):try
{
Regex re = new Regex("/mypattern/");
Console.WriteLine("The regular expression is valid.");
}
catch
{
Console.WriteLine("The regular expression is invalid!");
}If you move the
re
declaration outside, you can use it if it's valid after the catch (but then the catch should return or something to keep from trying to use the invalidRegex
object).-----BEGIN GEEK CODE BLOCK----- Version: 3.21 GCS/G/MU d- s: a- C++++ UL@ P++(+++) L+(--) E--- W+++ N++ o+ K? w++++ O- M(+) V? PS-- PE Y++ PGP++ t++@ 5 X+++ R+@ tv+ b(-)>b++ DI++++ D+ G e++>+++ h---* r+++ y+++ -----END GEEK CODE BLOCK-----
-
Just create a new instance of the
RegEx
. If the regex is invalid, an exception is thrown (this is documented in the class constructor information):try
{
Regex re = new Regex("/mypattern/");
Console.WriteLine("The regular expression is valid.");
}
catch
{
Console.WriteLine("The regular expression is invalid!");
}If you move the
re
declaration outside, you can use it if it's valid after the catch (but then the catch should return or something to keep from trying to use the invalidRegex
object).-----BEGIN GEEK CODE BLOCK----- Version: 3.21 GCS/G/MU d- s: a- C++++ UL@ P++(+++) L+(--) E--- W+++ N++ o+ K? w++++ O- M(+) V? PS-- PE Y++ PGP++ t++@ 5 X+++ R+@ tv+ b(-)>b++ DI++++ D+ G e++>+++ h---* r+++ y+++ -----END GEEK CODE BLOCK-----