【问题标题】:Python: regular expressions word matchPython:正则表达式单词匹配
【发布时间】:2015-10-13 06:31:44
【问题描述】:

我已经编写了这个小脚本,但我无法让 re.search 功能正常工作。我试图只匹配确切的单词(笑话),但 elif 语句不断返回打印,因为它在句子变量中找到笑话(来自小丑)。有没有办法让它计算单词笑话中的字母数量,所以只有当笑话是一个独立的词时它才是正确的?

#!/usr/bin/python
import re

sentence = 'The substantial treat shouts with the jokers'
find_emergency = re.search( r'emergency', sentence, re.M|re.I)
find_joke = re.search( r'joke', sentence, re.M|re.I)

if find_emergency :
   print 'Do you want to set this email as urgent?'
elif find_joke :  
  print "Do you want to mark this email as non-urgent?"
else :
   print "Sorry, we couldn\'t find what you were looking for ;("

【问题讨论】:

    标签: python regex python-2.7


    【解决方案1】:
    find_joke = re.search( r'\bjoke\b', sentence, re.M|re.I)
    

    为此使用\bword boundary

    【讨论】:

    • 谢谢@vks - 这正是我想要的
    【解决方案2】:

    您可以使用 vks 建议的单词边界方法。

    或者您可以使用“in”关键字执行基本搜索。

    #!/usr/bin/python
    import re
    
    sentence = 'The substantial treat shouts with the jokers'
    
    if 'emergency' in sentence :
       print 'Do you want to set this email as urgent?'
    elif 'joke' in sentence :  
      print "Do you want to mark this email as non-urgent?"
    else :
       print "Sorry, we couldn\'t find what you were looking for ;("
    

    【讨论】:

    • 仍然会匹配joker i.e)"joke" in "i am a joker" True
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    相关资源
    最近更新 更多