简体   繁体   English

正则表达式匹配前面的单词

[英]Regex to match preceding word

i'm attempting to extract the word 'Here' as 'Here' contains a capital letter at beginning of word and occurs before word 'now'. 我试图提取单词“ Here”,因为“ Here”在单词开头包含大写字母,出现在单词“ now”之前。

Here is my attempt based on regex from : 这是我基于regex的尝试:

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))

None is printed in above example. 在以上示例中未打印任何内容。

Have I implemented regex correctly ? 我是否正确实施了regex?

The following works for the given example: 对于给定的示例,以下工作:

Regex: 正则表达式:

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

Output: 输出:

'Here'

Explanation: 说明:

\\b imposes word boundary \\b加上单词边界

[AZ] requires that word begins with capital letter [AZ]要求单词以大写字母开头

[az]+ followed by 1 or more lowercase letters (modify as necessary) [az]+后接1个或多个小写字母(根据需要进行修改)

(?= now) positive look-ahead assertion to match now with leading whitespace (?= now)正向超前断言, now与领先的空白匹配

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM