与特定单词匹配的Python正则表达式

2024-04-26 05:34:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想匹配测试报告中包含“不确定”的所有行。 示例文本行:

'Test result 1: Not Ok -31.08'

我试过这个:

filter1 = re.compile("Not Ok")
for line in myfile:                                     
    if filter1.match(line): 
       print line

它应该可以根据http://rubular.com/工作,但是我在输出端什么也得不到。知道吗,有什么问题吗?测试了其他各种参数,如“.”和“^Test”,它们工作得很好。


Tags: intest文本re示例forifline
0条回答
网友
1楼 · 发布于 2024-04-26 05:34:59

你可以简单地使用

if <keyword> in str:
    print('Found keyword')

示例:

if 'Not Ok' in input_string:
    print('Found string')
网友
2楼 · 发布于 2024-04-26 05:34:59

你应该在这里使用re.search,而不是re.match

docsre.match

If you want to locate a match anywhere in string, use search() instead.

如果您要查找确切的单词'Not Ok',请使用\b单词边界,否则 如果你只是在寻找一个子串'Not Ok',那么使用simple:if 'Not Ok' in string

>>> strs = 'Test result 1: Not Ok -31.08'
>>> re.search(r'\bNot Ok\b',strs).group(0)
'Not Ok'
>>> match = re.search(r'\bNot Ok\b',strs)
>>> if match:
...     print "Found"
... else:
...     print "Not Found"
...     
Found
网友
3楼 · 发布于 2024-04-26 05:34:59

在这种情况下绝对不需要使用RegEx!只需使用:

s = 'Test result 1: Not Ok -31.08'
if s.find('Not Ok') > 0 : 
    print("Found!")

或者如前所述:

if 'Not Ok' in s:
    print("Found!")

相关问题 更多 >