Python正则表达式匹配多个单词

时间:2019-06-04 01:03:13

标签: python regex

我正在尝试捕获左侧in a class at the level ofas aexperiencewithwhich或{ {1}}。

样本输入:

;.

这是我当前的Python代码:

experience in a class at the level of Management Assistant which

结果应为:

content = 'experience in a class at the level of Management Assistant which'
result = re.search('(in a class at the level of|as a|experience)(.*?)(with|which|\;|\.)',content)

2 个答案:

答案 0 :(得分:2)

您执行此操作的方法是根据优先级排除其他对象。

(in[ ]a[ ]class[ ]at[ ]the[ ]level[ ]of|as[ ]a(?!.*?in[ ]a[ ]class[ ]at[ ]the[ ]level[ ]of)|experience(?!.*?(?:in[ ]a[ ]class[ ]at[ ]the[ ]level[ ]of|as[ ]a)))(.*?)(with|which|;|\.)

有点长,但是有效。

https://regex101.com/r/zduu9V/1

扩展

 (                             # (1 start)
      in [ ] a [ ] class [ ] at [ ] the [ ] level [ ] of
   |  as [ ] a
      (?!                           # Not this ahead
           .*? in [ ] a [ ] class [ ] at [ ] the [ ] level [ ] of
      )
   |  experience
      (?!
           .*? 
           (?:                           # Not these ahead
                in [ ] a [ ] class [ ] at [ ] the [ ] level [ ] of
             |  as [ ] a
           )
      )
 )                             # (1 end)
 ( .*? )                       # (2)
 ( with | which | ; | \. )     # (3)

答案 1 :(得分:1)

您的正则表达式模式略有不同,您可能还想在此处使用re.match,它可以在输入字符串的任何部分内找到一个匹配项,而不是re.search,它可以匹配整个输入。

content = 'experience in a class at the level of Management Assistant which'
result = re.match(r'\b(in a class at the level of|as a|experience) (.*?)\b(with|which|\;|\.)',content)
if (result):
    print "MATCH"