Regular expression for all abbreviated keyword variations

Viewed 58

I need to search for a keyword, such as "abcdef", which can also be in an abbreviated version with a dot at the end. All valid variants are:

abcdef
abcde.
abcd.
abc.
ab.
a.

I have a regular expression for this, which is clear:

abcdef|abcde\.|abcd\.|abc\.|ab\.|a\.

Another regular expression where the keyword characters are not repeated:

a(b(c(d(e(f|\.)|\.)|\.)|\.)|\.)

I'm looking for a more compact expression where not even a dot will be repeated. I use .NET syntax.

2 Answers

You can use a conditional construct:

a(b(c(d(e(?<f>f)?)?)?)?)?(?(f)|\.?)

See the regex demo. Here, (?<f>f)? is an optional named group matching f one or zero times. If the group matches, the f group is not empty, and (?(f)|\.?) matches an empty string then. If it is empty, \.? matches an optional ..

In PCRE falvor, could use

a(b(c(d(e(f(*ACCEPT))?)?)?)?)?\.?

where (*ACCEPT) verb inside an optional group would stop analyzing the current regex and return the value matched so far (so the last \.? would not be tried if f is found). See this regex flavor.

As a variant:
a(bcdef|(bcde|bcd|bc|b|)\.)

With shorting 2 letters (a bit shorter):
a(bcdef|(b(cde|cd|c|)|)\.)
With shorting 3 letters (the same length):
a(bcdef|(b(c(de|d|)|)|)\.)

With shorting 4 letters the shortest - 25 symbols:
a(bcdef|(b(c(de?|)|)|)\.)

Related