Regex select all before this or that

Viewed 111

I want to split my string so it will take everything before NK-, SK-, DJ- or MU-

DJXFSE DJ-13 - ABC
MUEKOP MU-27 - ABC
DJXFSE DJ-12 - ABC
NOVA KNSEAC NK-26-4 - ABC
NOVA KNSEAC NK-26-9 - ABC
SRFI KRSIXUR SK-45 ABC2

So the output would be

DJXFSE
MUEKOP 
DJXFSE 
MUEKOP 
DJXFSE 
NOVA KNSEAC
NOVA KNSEAC
SRFI KRSIXUR

What would be the way to choose everything before (excluding) different possibilities of characters? I tried this

(^.*(?=(\ DJ)|(\ MU)))

where i thought that this part (\ DJ)|(\ MU) would mean DJ or MU, but i am obviously totally wrong.

2 Answers

With your shown samples, could you please try following. Online regex demo is: Online regex demo

^.+(?= (?:DJ|MU|[NS]K)-)

Explanation:

^.+              ##From starting looking till everything if further mentioned look ahead is true.
(?=              ##Starting positive look ahead from here.
(?:              ##Starting a non capturing group here
  DJ|MU|[NS]K    ##Looking for either DJ OR MU OR NK OR SK here.
)                ##Closing non capturing group here.
-)               ##mentioning -(dash) and closing positive look ahead here.


EDIT: As per OP's comment adding following solution here too.

^(.+)( (DJ|MU|[NS]K)-)

Online demo for above is: Online demo for above regex

You can use

^(.*?)(?:\s+(?:DJ|MU|[NS]K)-)

See the regex demo.

Details

  • ^ - start of string
  • (.*?) - Group 1: any zero or more chars other than line break chars as few as possible
  • (?:\s+(?:DJ|MU|[NS]K)-) - a non-capturing group:
    • \s+ - one or more whitespaces
    • (?:DJ|MU|[NS]K) - DJ, MU, NK or SK
    • - - a hyphen.

NOTE: If the suffixes can go missing and you need to match till end of string, you will need to add |$ to the non-capturing group:

^(.*?)(?:\s+(?:DJ|MU|[NS]K)-|$)
Related