[英]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.