简体   繁体   English

Python:如何使用正则表达式仅匹配一个单词

[英]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) 上面的正则表达式将选择所有具有单词(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 ? 那么他们是一种只有在出现三个单词之一的情况下才选择行的方法吗?

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 Regex101上的演示

how about using re.findall instead and check for only 1 item match, match only True when re.findall return only single match item 如何改用re.findall并仅检查1个匹配项,仅匹配true,而re.findall仅返回单个匹配项

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM