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:

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

Leave a Reply