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

Matching a string but ignoring an optional suffix?

I would like to capture the beginning of a string but ignore an optional suffix View.

Possible inputs:

Shell
ShellView
Console
ConsoleView

Expected outputs:

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

Shell
Shell
Console
Console

This expression is obviously wrong, the question mark makes everything captured by the first group:

(\w+)(View)?

If I use an expression like (Shell)(View)? it does work but then only for strings that begin with Shell, nothing else of course.

Question:

How should such regex pattern be written ?

>Solution :

You can use

^(\w+?)(?:View)?$

See the regex demo. Details:

  • ^ – start of string
  • (\w+?) – Group 1: any one or more word chars, as few as possible
  • (?:View)? – an optional non-capturing group matching a View char sequence one or zero times
  • $ – end of string.

See a C# demo:

var texts = new List<string> { "Shell", "ShellView", "Console", "ConsoleView" };
var rx = new Regex(@"^(\w+?)(View)?$"); 
foreach (var text in texts) 
{
    var match = rx.Match(text)?.Groups[1].Value;
    Console.WriteLine(match);
}

Output:

Shell
Shell
Console
Console
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