'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 1:[1]

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

Solution 2:[2]

Here is another way to do it, which seems to be fast (98 steps).

^\w+?(?=View$|$)

Here is the online demo.


  • ^: Start of the String
  • \w+?: Matches any word character between one and unlimited times, as few as possible.
  • (?=): Positive lookahead.
    • View$: Matches View at the end of the string
    • |: Or
    • $: End of the string

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Cubix48