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 regexpattern 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 ...

Get Regular Expressions Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.