Using RegEx to find if text includes something you don't want?

Question:

I have this code:

import re

txt = "If MARA.MTART in ('ZPLW', 'ZFTW') and MARM.MEINH = 'CS', then AUSP.MATNR exists in MARC.MATNR"

x = re.search("MARA.", txt)

if x:
  print(Match")
else:
  print("No match")

I want it to be "No Match" if there is any another prefix before the "." besides MARA. So this one should say no match because there is "MARM."

but this one

txt = "If MARA.MTART in ('ZPLW', 'ZFTW'), then MARA.MATNR = 1111"

would say Match

Asked By: Owen

||

Answers:

Maybe are you looking for something like this?

x = all(['MARA.' in x for x in re.findall('[A-Z0-9]+.[A-Z0-9]+', txt)])
Answered By: MaryRa

You can use re.findall() to create a list of these prefixes using this regular expression (based off of the text you provided: w{4}.

So you could use it like this to make a list:

prefixes = re.findall(r"w{4}.",txt)

which is equal to ['MARA.', 'MARM.', 'AUSP.', 'MARC.']

Use this to check that they’re all equal to "MARA." like this:

all(element == "MARA." for element in re.findall(r"w{4}.",txt))
False
Answered By: Joe Carboni
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.