Home > OS >  How to capture hyphen, space or none and ignore case?
How to capture hyphen, space or none and ignore case?

Time:01-20

I am trying to write a Regex in C# to capture all these potential strings:

Test Pre-Requisite
Test PreRequisite
Test Pre Requisite

Of course the user could also enter any possible case. So it would be great to be able to ignore case. The best I can do is:

Regex TestPreReqRegex = new Regex("Test Pre[- rR]");
If (TestPreReqRegex.IsMatch(StringToCompare)){
    // Do Stuff
}

But this doesn't capture "Test PreRequisite" and also doesn't capture lower case. How can I fix this? Any help is much appreciated.

CodePudding user response:

If you're trying to match the entire string, use:

Regex TestPreReqRegex = new Regex("^Test Pre[- ]?Requisite$", RegexOptions.IgnoreCase);

If you're looking for partial matches, then change the pattern to:

\bTest Pre[- ]?Requisite

Or:

\bTest Pre[- ]?R

Pattern details:

  • ^ - Beginning of string.
  • \b - Word boundary.
  • [- ]? - Match a hyphen or a space character between zero and one times.
  • $ - End of string.

C# Demo:

var inputs = new[] 
    { "Test Pre-Requisite", "Test PreRequisite", "Test Pre Requisite" };
Regex TestPreReqRegex = new Regex("^Test Pre[- ]?Requisite$",
                                  RegexOptions.IgnoreCase);
foreach (string s in inputs)
{
    Console.WriteLine("'{0}' is {1}'.", s,
                      TestPreReqRegex.IsMatch(s) ? "a match" : "not a match");
}

Output:

'Test Pre-Requisite' is a match'.
'Test PreRequisite' is a match'.
'Test Pre Requisite' is a match'.

Try it online.

  •  Tags:  
  • Related