【问题标题】:Python regex to match a specific wordPython正则表达式匹配特定单词
【发布时间】:2013-06-10 00:29:02
【问题描述】:

我想匹配测试报告中包含“Not Ok”字样的所有行。 文本示例:

'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" ,它们工作得很好。

【问题讨论】:

  • 如果它是一个特定的字符串,为什么要使用正则表达式?为什么不if "Not Ok" in line:
  • 顺便说一句,re.match() 只匹配字符串的开头。
  • 我确信 match 不仅可以做字符串的开头.. $ 不应该匹配行尾吗?
  • 也许我不清楚:re.match("a")re.search("^a") 相同。 re.match("Not Ok") 将为"Not Ok Joe!" 返回True,为"It's Not Ok!" 返回False
  • 啊,我明白了。从 Python 文档中不是很清楚。每天学习新东西!

标签: python regex match


【解决方案1】:

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

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

或如前所述:

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

【讨论】:

    【解决方案2】:

    你可以简单地使用,

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

    例子:

    if 'Not Ok' in input_string:
        print('Found string')
    

    【讨论】:

      【解决方案3】:

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

      来自docsre.match

      如果您想在字符串中的任何位置找到匹配项,请改用 search()。

      如果您要查找确切的单词 'Not Ok',则使用 \b 单词边界,否则 如果您只是在寻找子字符串 'Not Ok',请使用简单的: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
      

      【讨论】:

      • 确实,即使没有所有额外的 \b 东西,这也有效。谢谢!我还发现 re.findall 在这种情况下有效。
      • @casper 没有\b 它也会返回True 类似的东西:'KNot Oke're.findall 返回所有非重叠匹配的列表,用于检查目的 re.search 是最佳选择。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-29
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-13
      相关资源
      最近更新 更多