Lets assume I have some string in python ending with some number.
2te2xt12
text1
text143
te2xt341
How can I get the right most number sequence:
2te2xt12 >> 12
text1 >> 1
text143 >> 143
te2xt341 >> 341
Is there a simple and easy way.
I know nothing about re
Thanks in advance
import re
s=r"""1231ololo767980716"""
re.match('.*?([0-9]+)$', s).group(1)
>>> '767980716'
or
next(re.finditer(r'\d+$', s)).group(0)
>>> '767980716'
Explanation of regexp components:
.*?
is a non-greedy match and consumes only as much as possible (a greedy match would consume everything except for the last digit).
[0-9]
and \\d
are two different ways of capturing digits. Note that the latter also matches digits in other writing schemes, like ୪
or ൨
+
means multiple entries (at least one number at the end). $
matches only the end of the input. and all components you can find here: https://www.rexegg.com/regex-quickstart.html very helpful cheat sheet
This code which uses regex \\d+$
should get you what you are exactly looking for,
import re
arr = ['2te2xt12',
'text1',
'text143',
'te2xt341']
for s in arr:
m = re.search(r'\d+$', s)
if (m):
print(s + ' >> ' + m.group())
Prints,
2te2xt12 >> 12
text1 >> 1
text143 >> 143
te2xt341 >> 341
Try this? The function test should do what you need.
import re
def test(string):
m = re.search(r'\d+$', string)
if m is not None:
print(m.group())
It is quite simple using regex in python
re.findall('\d+$',yourString)[0]
To know more about regular expressions refer the docs here
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.