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

Time:08-02

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

CodePudding user response:

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

CodePudding user response:

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)])
  • Related