Ravi Yadav
Ravi Yadav

Reputation: 405

Python : How to match only one of the words using regular expression

regular_expression = re.compile(r'SKIPPED|PASSED|FAILED')
regular_expression.search(line)

The above regular expression will selected all the lines that have one of the words(SKIPPED|PASSED|FAILED)

Problem is : It selects the below line also

TYPE   TOTAL   SKIPPED      PASSED    FAILED
----   -----   -------      ------    ------

Module   21      0            19        3

So is their a way so that it selects line only if one of the three words are present ?

Upvotes: 0

Views: 44

Answers (2)

Skycc
Skycc

Reputation: 3555

how about using re.findall instead and check for only 1 item match, match only True when re.findall return only single match item

regular_expression = re.compile(r'SKIPPED|PASSED|FAILED')
match = len(regular_expression.findall(line)) == 1

Upvotes: 1

Sebastian Lenartowicz
Sebastian Lenartowicz

Reputation: 4874

Nobody sane would recommend doing this with a regex in production code, but for the sake of completeness, here's an answer using positive and negative lookaheads:

^(?:(?=.*PASSED)(?!.*(?:FAILED|SKIPPED))|(?=.*FAILED)(?!.*(?:PASSED|SKIPPED))|(?=.*SKIPPED)(?!.*(?:FAILED|PASSED)))

Basically, what it'll do is look ahead to ensure that the string contains any one of the words that you want, then look ahead again to make sure it doesn't contain either of the other two.

Demo on Regex101

Upvotes: 1

Related Questions