簡體   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