Match start or end of string - but only specify pattern once

Viewed 82

Ok, this is mostly an intellectual question (or an improvement).

I have a pattern that must match either start OR end of string (or both).

(Here I simply use 'abcd' as pattern, but in real world, it's a rather long and complex pattern. However that's not interesting, since it works).

As usual I use this regex:

@"^abcd|abcd$"

Here, the pattern is duplicated, once for start and once for end of string.

However, since the pattern is long and complicated, I would like to specify it only once in the string. That would help reading as well as maintaining - I would only have one place to change.

The following regexes do of course not work, but give an idea of what I want:

@"^abcd$" - matches only 'abcd' exact
@"^?abcd$?" - matches also 'abcd' in the middle

So, the question is:

Is there a way to match either start or end of string and only specify the inner pattern once?

1 Answers

You may use

(^)?abcd(?(1)|$)

See the regex demo.

Details

  • (^)? - an optional capturing group, its value will be an empty string if the position was matched or null otherwise
  • abcd - your value
  • (?(1)|$) - a conditional construct: if Group 1 value is not null (if it was matched) then do nothing, else, match the end of string.

See the C# demo:

var strings = new List<string> { "1 abcd", "abcd 1", "1 abcd 1"};
var pattern = "(^)?abcd(?(1)|$)";
foreach (var s in strings)
{
    Console.WriteLine("{0} => {1}", s, Regex.IsMatch(s, pattern));
}

Output:

1 abcd => True
abcd 1 => True
1 abcd 1 => False
Related