To validate a regular expression in C#, you can use the Regex.IsMatch
method. This method takes two parameters: the input string to be validated, and the regular expression pattern to use for validation.
Here is an example of how to use Regex.IsMatch
for validation:
main.cs213 chars12 lines
In this example, the regular expression pattern \bexample\b
matches the word "example" when it appears as a separate word (note the \b
boundary markers). If the input string contains the word "example", the IsMatch
method will return true and the "Input is valid." message will be printed to the console.
If the regular expression pattern is not valid, an exception will be thrown. To avoid this, you can use the Regex.TryCreate
method to create a Regex
object from the pattern string, like so:
main.cs246 chars12 lines
In this example, the TryCreate
method attempts to create a Regex
object from the pattern string with a timeout of one second. If successful, the regex
variable can be used for validation.
gistlibby LogSnag