Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading