How to match everything before a pattern, until reach another pattern

Viewed 27

With Python regex, I'm trying to match everything before a pattern (including line breakers), until reach another pattern. This is the Text:

DFGC 2836 -07-0411B
IMUD - DHI211 (MOOYEHBF P/ SHDUF)
C7000039694 (PD MOFIBD PODF BAOJFD)

The code below matches everything before "C700" pattern. I need everything before "C700", BUT limited to "IMUD" (including it). So, the result should be "IMUD - DHI211 (MOOYEHBF P/ SHDUF)"

(?s)^.+?(?=C700\d*(?=\s))

See it in regex101: LINK

1 Answers

Here's a simple regex to do this:

pattern = re.compile(r'(IMUD .*?)(C700)', flags=re.DOTALL)

Explanation:

  • The first group (IMUD .*?) captures everything after IMUD in a non-greedy way (means it stops capturing when the 2nd capturing group, (C700) is found
  • we use the flag re.DOTALL so that the . also match new lines \n

To get what you want, only retrieve the first group matched

s = """DFGC 2836 -07-0411B
IMUD - DHI211 (MOOYEHBF P/ SHDUF)
C7000039694 (PD MOFIBD PODF BAOJFD)"""

res = pattern.search(s).group(1)
res
>>> 'IMUD - DHI211 (MOOYEHBF P/ SHDUF)\n'
Related