Regex pattern with (start of line or start of string or underscore)

Viewed 25

i wonder if you can help me with regex pattern... in this input:

VEX_BLE_NW_maRIu
VEP_AS_maSAusz_TXZ
NE_lapKS_US

I want to find prefixes and Suffixes in those 3 names. Like "VEX" "BLE" "NW" "VEP" "AS" "TXZ" "NE" "US"

My pattern is now ([A-Z]{2,3})[_\s] I have a problem to make (start of line or start of string or underscore) and also (end of line or end of string or underscore or space)

Thanks in advance!

1 Answers

You can use

(?<![^_])[A-Z]{2,3}(?![^_])

See the regex demo.

Alternative patterns are

(?<=_|^)[A-Z]{2,3}(?=_|$)
(?:_|^)([A-Z]{2,3})(?=_|$)

In case of (?:_|^)([A-Z]{2,3})(?=_|$), the result is in Group 1.

Details:

  • (?<![^_]) - either start of string or a location immediately preceded with _
  • [A-Z]{2,3} - two or three uppercase ASCII letters
  • (?![^_]) - either end of string or a location immediately followed with a _ char.
Related