3.5. Test Whether a Match Can Be Found Within a Subject String
Problem
You want to check whether a match can be found for a particular regular
expression in a particular string. A partial match is sufficient. For
instance, the regex ‹regex●pattern› partially
matches The regex
pattern can be found. You don’t care about any of the
details of the match. You just want to know whether the regex matches
the string.
Solution
C#
For quick one-off tests, you can use the static call:
bool foundMatch = Regex.IsMatch(subjectString, "regex pattern");If the regex is provided by the end user, you should use the static call with full exception handling:
bool foundMatch = false;
try {
foundMatch = Regex.IsMatch(subjectString, UserInput);
} catch (ArgumentNullException ex) {
// Cannot pass null as the regular expression or subject string
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}To use the same regex repeatedly, construct a Regex object:
Regex regexObj = new Regex("regex pattern");
bool foundMatch = regexObj.IsMatch(subjectString);If the regex is provided by the end user, you should use the
Regex object with
full exception handling:
bool foundMatch = false;
try {
Regex regexObj = new Regex(UserInput);
try {
foundMatch = regexObj.IsMatch(subjectString);
} catch (ArgumentNullException ex) {
// Cannot pass null as the regular expression or subject string
}
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}VB.NET
For quick one-off tests, you can use ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access