Regexp for "either/or" but not "neither"

Viewed 307

Working with Notepad++ v7.9 here.

Suppose R is a complex regexp pattern. I now want to match _R, R_, or_R_ but not R alone. How to do this without writing explicitly (_R|R_|_R_)? This requires R being written out three times and looks ugly.

The closest I can think of is _?R_? but this also matches R alone (and is in fact equivalent to it), which is a false positive to me.

In between is (_?R_|_R_?) but R is repeated again here, though one less time.

1 Answers

You may use If-Then-Else as follows:

(_)?R(?(1)_?|_)

Demo.

This enables you to write R only once.

Breakdown:

(_)?        # An optional capturing group that matches an underscore character.
R           # Matches 'R' literally (replace it with your pattern).
(?          # If...
    (1)     # ..the first capturing group is found,...
    _?      # ..then match zero or one underscore characters (optional).
|           # Else (otherwise)...
    _       # Match exactly one underscore character (required).
)           # End If.

Works in Notepad++:

Notepad++ demo

Related