Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 287
Charles Avatar asked Dec 30 '22 19:12

Charles


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

like image 195
41686d6564 stands w. Palestine Avatar answered Jan 11 '23 21:01

41686d6564 stands w. Palestine