非捕获组的正则表达式前瞻未按预期工作
Regex look-ahead with non-capturing group not working as intended
下面是我要从中提取月份(在本例中为 7 月)的文本。
word_pattern
确保文本包含这些词,
而 month_pattern
将提取月份。所以首先我验证文本段落
包含某些词,如果包含,那么我会尝试提取 month
单独使用模式时,它们会匹配,但如果我尝试组合它们
我最终没有匹配。
我不知道我做错了什么。
import re
text = ''' The number of shares of the
registrant’s common stock outstanding as
of July 31, 2017 was 52,833,429.'''
# patterns
word_pattern = r'(?=.*outstanding[.,]?)(?=.*common)(?=.*shares)'
month_pattern = r'(Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|(Nov|Dec)(?:ember)?)'
pattern = word_pattern + month_pattern
print(re.search(pattern, text, flags = re.IGNORECASE|re.DOTALL))
预期结果:
正则表达式不能像那样轻易连接。问题是您的单词模式仅使用前瞻,因此不会向前移动位置,这在月份仅出现时成为问题 mid-string。因此,您需要使用弥合间隙的量词允许光标前进到月份位置,例如.*
试试
(?=.*outstanding[.,]?)(?=.*common)(?=.*shares).*(Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|(Nov|Dec)(?:ember)?)
或者 pattern = word_pattern +'.*'+ month_pattern
应该可以解决问题。
结果可以在捕获组1中找到:re.search(...).group(1)
下面是我要从中提取月份(在本例中为 7 月)的文本。
word_pattern
确保文本包含这些词,
而 month_pattern
将提取月份。所以首先我验证文本段落
包含某些词,如果包含,那么我会尝试提取 month
单独使用模式时,它们会匹配,但如果我尝试组合它们 我最终没有匹配。 我不知道我做错了什么。
import re
text = ''' The number of shares of the
registrant’s common stock outstanding as
of July 31, 2017 was 52,833,429.'''
# patterns
word_pattern = r'(?=.*outstanding[.,]?)(?=.*common)(?=.*shares)'
month_pattern = r'(Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|(Nov|Dec)(?:ember)?)'
pattern = word_pattern + month_pattern
print(re.search(pattern, text, flags = re.IGNORECASE|re.DOTALL))
预期结果:
正则表达式不能像那样轻易连接。问题是您的单词模式仅使用前瞻,因此不会向前移动位置,这在月份仅出现时成为问题 mid-string。因此,您需要使用弥合间隙的量词允许光标前进到月份位置,例如.*
试试
(?=.*outstanding[.,]?)(?=.*common)(?=.*shares).*(Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|(Nov|Dec)(?:ember)?)
或者 pattern = word_pattern +'.*'+ month_pattern
应该可以解决问题。
结果可以在捕获组1中找到:re.search(...).group(1)