正则表达式匹配前一个单词

时间:2018-03-29 16:35:32

标签: python regex

我试图提取单词' Here'作为'在这里'在单词的开头包含一个大写字母,并出现在单词' now'。

之前

以下是基于正则表达式的尝试:

regex match preceding word but not word itself

import re
sentence = "this is now test Here now tester"
print(re.compile('\w+(?= +now\b)').match(sentence))

以上示例中没有打印。

我是否正确实施了正则表达式?

1 个答案:

答案 0 :(得分:2)

以下适用于给定示例:

正则表达式:

re.search(r'\b[A-Z][a-z]+(?= now)', sentence).group()

输出:

'Here'

说明:

\b强加了字边界

[A-Z]要求该字以大写字母

开头

[a-z]+后跟一个或多个小写字母(必要时修改)

(?= now)肯定的前瞻声明,以便将now与前导空格匹配