Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

regex - Regular expression matching A, B, and AB

I would like to create a regular expression that matches A, B, and AB, where A and B are quite complex regular expressions.

One solution is to use (A|A?B) or (AB?|B), but then I have to repeat one of the expressions.

A?B? does not work, since this also matches the empty string.

Is it possible to create this regular expression without repeating neither A nor B?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In general, it is not possible. You may use some workarounds though.

If A and B start and end with word characters

In case the A and B are or start/end in word type characters (letters, digits or _, you may use

(?<!w)A?(?:B)?(?!w)(?<!W(?!w))(?<!^(?!w))

See the regex demo

  • (?<!w) - no word character allowed before
  • A? - an optional A
  • (?:B)? - an optional B
  • (?!w) - no word char is allowed right after (at this point, we may match empty strings between start of string and a non-word char, between a non-word and end of string or between two non-word chars, hence we add...)
  • (?<!W(?!w)) - no match allowed if right before is a non-word char that is not followed with a word char (this cancels empty matches between two non-word chars and a non-word char and end of string)
  • (?<!^(?!w)) - no match allowed at the start of string if not followed with a word char.

Avoid repeating part of the expression in an alternation based pattern

In PCRE, you may avoid repeating the same pattern part since you may recurse subpatterns with subroutine calls:

A(?<BGroup>B)?|(?&BGroup)

See the regex demo.

The (?<BGroup>B) is a named capturing group whose pattern is repeated with the (?&BGroup) named subroutine call.

See Recursive patterns.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...