![](/img/trans.png)
[英]PERL How to match last n digits of a string with n consecutive digits or more?
[英]How to get N consecutive digits from a string?
我試圖從匹配的字符串中獲取4個連續數字。
當我嘗試re.sub('[^\\d]+', ',', "abc 23 [1981] ghj [5656]")
它返回,23,1981,5656,
.so當我這樣做re.sub('[\\d]{4}+', ',', "abc 23 [2021]")
,則會返回錯誤"multiple repeat at position 7"
由於我保留{4}
,所以它不應該匹配4次[\\d]
並返回,1981,5656,
嗎?
如果只想使用正則表達式,則需要一點技巧。
相反,您可以使用lambda有條件地用逗號替換不是四位數的字符串部分,並按原樣保留這四位數。 嘗試使用此Python代碼,
import re
s = "abc 23 [1981] ghj [5656]"
print(re.sub(r'\b(\d{4})\b|((?!\b\d{4}\b).)+', lambda x: x.group() if x.group(1) else ',', s))
按照您的需要打印,
,1981,5656,
我們在這里所做的是,在group1中使用\\b(\\d{4})\\b
捕獲四位數字,並使用此((?!\\b\\d{4}\\b).)+
正則表達式,然后進行條件替換,如果第一個替換匹配,則group1不為空,因此將其替換為匹配的文本;如果group1為空,則表示第二個正則表達式已匹配,因此使用逗號替換。
使用re.findall
例如:
import re
s = "abc 23 [1981] ghj [5656]"
print(re.findall(r"\[(\d{4})\]", s))
輸出:
['1981', '5656']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.