Python regex to match a specific word

后端 未结 3 723
感情败类
感情败类 2020-12-30 05:32

I want to match all lines in a test report, which contain words \'Not Ok\'. Example line of text :

\'Test result 1: Not Ok -31.08\'

I tried

3条回答
  •  时光取名叫无心
    2020-12-30 06:34

    You should use re.search here not re.match.

    From the docs on re.match:

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

    If you're looking for the exact word 'Not Ok' then use \b word boundaries, otherwise if you're only looking for a substring 'Not Ok' then use 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
    

提交回复
热议问题