简体   繁体   中英

How to extract digits from string and return the last 3 or less using regex

Consider the string s

s = 'hello1 my45-fr1@nd5'

I want to strip out the last 3 digits '515' . I know I can do

import re

re.sub(r'\D', '', s)[-3:]

'515'

However, I need a single regex substitution that performs the same task.

You can use this re.sub using a lookahead:

>>> s = 'hello1 my45-fr1@nd5'
>>> print re.sub(r'\D+|\d(?=(?:\D*\d){3,}\D*$)', '', s)
515

RegEx Demo

RegEx Breakup:

\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

Positive Lookahead (?=(?:\\D*\\d){3,}\\D*$) asserts that we have at least 3 digits ahead of us from current position.

Using a bit of brute force and capturing groups, you can use

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

and replace it with

\1\2\3

See https://regex101.com/r/h2bFeV/2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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