Home > OS >  Matching one of three letters on one side of an underscore if not preceded or followed with alphanum
Matching one of three letters on one side of an underscore if not preceded or followed with alphanum

Time:12-02

I have two phrases:

V_AEH1_N
S_D_R_AXH0

This is my regex so far:

r"(_(N|D|S)(?=[^a-zA-Z0-9]))|((?=[^a-zA-Z0-9])(N|D|S)_)"

which mathces only _D in the 2nd phrase. The desired outcome is to match both S_ & D_ and also _N from the first phrase.

CodePudding user response:

You can use

(?<![^\W_])[NDS]_|_[NDS](?![^\W_])

See the regex demo. Details:

  • (?<![^\W_])[NDS]_ - N, D or S and an underscore after if not preceded with a non-alphanumeric char ((?<![^\W_]) is a leading word boundary here with _ "subtracted" from it)
  • | - or
  • _[NDS](?![^\W_]) - an underscore and then either N, D or S if not followed with a non-alphanumeric char ((?![^\W_]) is a trailing word boundary here with _ "subtracted" from it).
  • Related