简体   繁体   中英

Extract number (dash included) from string using regex in Python

Hello and thanks for helping.

String examples:

"Hello 43543" ---> "43543"
"John Doe 434-234" ---> "434-234"

I need a regex to extract the examples on the right.

If all your strings are like this, you can achieve the same without re :

s = "John Doe 434-234"
n = s.split()[-1] 

print(n)

>>> "434-234"

It will split your string on spaces and give you the last field.

I would do it following way:

import re
pattern = r'\d[0-9\-]*'
number1 = re.findall(pattern,'Hello 43543')
number2 = re.findall(pattern,'John Doe 434-234')
print(number1[0]) #43543
print(number2[0]) #434-234

My solution assumes that you are looking for any string starting with digit and with all other characters being digit or - , this mean it will also grab for example 4--- or 9-2-4--- and so on, however this might be not issue in your use case.

I want to note that before writing pattern, you should answer question: what it should match exactly ? My pattern works as intended for examples you given, but keep in mind that this do NOT automatically mean it would give desired output with all data you might want to process using it.

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