user976557
user976557

Reputation: 13

python regular expression exclude from match string

I have 3 strings

a ="keep the your pass ABCDEFG other text"
b ="your pass: TESTVALUE other text"
c ="no pass required other text"

I want to get capital values after pass, like this

re.match(r'.*\spass:?\s([a-zA-Z]+).*',a,re.I).group(1)
re.match(r'.*\spass:?\s([a-zA-Z]+).*',b,re.I).group(1)

but I want to exclude "no pass", which is I don't want re to match to c string, how do I do that?


Solution: Thanks eyquem and ovgolovin

I will take eyquem's suggestion of re.search('no\s+pass|pass:?\s+([A-Z]+)')

Upvotes: 1

Views: 7479

Answers (3)

eyquem
eyquem

Reputation: 27585

import re

for x in ("keep the your pass ABCDEFG other text",
          "your pass: TESTVALUE other text",
          "no pass required other text"):
    print re.search('no\s+pass|pass:?\s+([A-Z]+)',x).group(1)
A-Z]+)'

result

ABCDEFG
TESTVALUE
None

Upvotes: 3

mb14
mb14

Reputation: 22636

A solution would be to first , filter everything which doesn't contains 'no pass' and then search for pass. Doing two steps might seem a bit heavy but you will avoid lots of problems by doing it this way. You are trying to solve two problems at the same time (and apparently you are struggling to do it) so just separate the two problems.

Upvotes: 1

ovgolovin
ovgolovin

Reputation: 13430

It's not OK to use match here. It's preferable to use search for such cases.

re.search(r'(?<!no\s)pass:?\s+([A-Z]+)',a).group(1)

It would be better to write it this way:

re.search(r'(?<!no\s*)pass:?\s+([A-Z]+)',a).group(1)

, but unfortunatelly the current version of regex engine doesn't support infinite lookbehinds.

Upvotes: 1

Related Questions