[英]How to extract digits from string and return the last 3 or less using regex
考慮字符串s
s = 'hello1 my45-fr1@nd5'
我想刪除最后3位'515'
。 我知道我能做到
import re
re.sub(r'\D', '', s)[-3:]
'515'
但是,我需要一個執行相同任務的正則表達式替換。
您可以使用前瞻使用此re.sub
:
>>> s = 'hello1 my45-fr1@nd5'
>>> print re.sub(r'\D+|\d(?=(?:\D*\d){3,}\D*$)', '', s)
515
RegEx分手:
\D+ # match 1 or more non-digits
| # OR
\d # match a digit
(?=(?:\D*\d){3,}\D*$) # that is followed by 3 or more digits in the string
正向前瞻(?=(?:\\D*\\d){3,}\\D*$)
斷言我們從當前位置至少有3位數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.