簡體   English   中英

Python正則表達式-findall和sub中的不同結果

[英]Python Regex - Different Results in findall and sub

我正在嘗試用“ BRUNCH”代替出現的“ brunch”工作。 我使用的是正則表達式,可以正確識別出現的情況,但是當我嘗試使用re.sub時,它用re.findall代替了更多的文本。 我正在使用的正則表達式是:

re.compile(r'(?:^|\.)(?![^.]*saturday)(?![^.]*sunday)(?![^.]*weekend)[^.]*(brunch)',re.IGNORECASE)

字符串是

str = 'Valid only for dine-in January 2 - March 31, 2015. Excludes brunch, happy hour, holidays, and February 13 - 15, 2015.'

我希望它產生:

'Valid only for dine-in January 2 - March 31, 2015. Excludes BRUNCH, happy hour, holidays, and February 13 - 15, 2015.'

步驟:

>>> reg.findall(str)
>>> ['brunch']
>>> reg.sub('BRUNCH',str)
>>> Valid only for dine-in January 2 - March 31, 2015BRUNCH, happy hour, holidays, and February 13 - 15, 2015.

編輯:

我使用的最終解決方案是:

re.compile(r'((?:^|\.))(?![^.]*saturday)(?![^.]*sunday)(?![^.]*weekend)([^.]*)(brunch)',re.IGNORECASE)
re.sub('\g<1>\g<2>BRUNCH',str)

re.sub使用

(^|\.)(?![^.]*saturday)(?![^.]*sunday)(?![^.]*weekend)([^.]*)(brunch)

替換為\\1\\2BRUNCH 。請\\1\\2BRUNCH演示。

https://regex101.com/r/eZ0yP4/16

通過正則表達式:

(^|\.)(?![^.]*saturday)(?![^.]*sunday)(?![^.]*weekend)([^.]*)brunch

DEMO

\\1\\2BRUNCH替換匹配的字符

為什么匹配比brunch更重要

因為您的正則表達式實際上比早午餐更匹配

請參閱正則表達式如何匹配的鏈接

為什么在findall不顯示?

因為您只在brunch中包裹了brunch

>>> reg = re.compile(r'(?:^|\.)(?![^.]*saturday)(?![^.]*sunday)(?![^.]*weekend)[^.]*(brunch)',re.IGNORECASE)
>>> reg.findall(str)
['brunch']

將所有([^.]*brunch)包裹在括號中

>>> reg = re.compile(r'(?:^|\.)(?![^.]*saturday)(?![^.]*sunday)(?![^.]*weekend)([^.]*brunch)',re.IGNORECASE)
>>> reg.findall(str)
[' Excludes brunch']
  • re.findall忽略那些沒有字幕的內容

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM