繁体   English   中英

如何从字符串中提取数字并使用正则表达式返回最后3个或更少

[英]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演示

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位数字。

使用一点蛮力和捕获组,你可以使用

.*(\d)\D*(\d)\D*(\d)\D*$

并替换它

\1\2\3

请参阅https://regex101.com/r/h2bFeV/2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM