首页 文章

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

提问于
浏览
-1

我试图提取“Here”这个词,因为“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 回答

  • 2

    以下适用于给定示例:

    正则表达式:

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

    输出:

    'Here'
    

    说明:

    \b 强加词边界

    [A-Z] 要求该单词以大写字母开头

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

    (?= now) 正向前瞻断言,将 now 与前导空格相匹配

相关问题