正则表达式模式以查找字符串中的特定单词

时间:2018-07-10 15:33:08

标签: regex python-3.x

我想要一个简单的正则表达式模式来找到字符串中的特定单词。例如,在下面的代码中,我想查找一个字符串是否包含单词“ wings”。

import re

   body = """

   Beginning on Wednesday, April 13, contractors will commence renovation of     the
    floors, staircase, ceilings and restrooms in Core 5 of the Phase I Academic
    Building (the area between wings D and E). During construction, access to Core..


   """

   if re.search('\bwings\b', body, re.IGNORECASE):
      print("Matches")
   else:
      print("Does not match")

上面的代码是否应该打印“匹配”,因为字符串“ body”中存在单词“ wings”?我尝试在regex 101中测试我的regex模式,并且我的模式在那里工作。我不知道为什么它在python中不起作用。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

在正则表达式模式之前使用原始字符串r

例如:

import re

body = """
Beginning on Wednesday, April 13, contractors will commence renovation of the floors, staircase, ceilings and restrooms in Core 5 of the Phase I Academic Building (the area between wings D and E). During construction, access to Core..
"""

if re.search(r'\bwings\b', body, re.IGNORECASE):
    print("Matches")
else:
    print("Does not match")