Home > Back-end >  Matching a string but ignoring an optional suffix?
Matching a string but ignoring an optional suffix?

Time:03-16

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 ?

CodePudding user response:

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

CodePudding user response:

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
  • Related