我试图提取“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 回答
以下适用于给定示例:
正则表达式:
输出:
说明:
\b
强加词边界[A-Z]
要求该单词以大写字母开头[a-z]+
后跟一个或多个小写字母(必要时修改)(?= now)
正向前瞻断言,将now
与前导空格相匹配