Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

regex - Python - Check if the last characters in a string are numbers

Basically I want to know how I would do this.

Here's an example string:

string = "hello123"

I would like to know how I would check if the string ends in a number, then print the number the string ends in.

I know for this certain string you could use regex to determine if it ends with a number then use string[:] to select "123". BUT if I am looping through a file with strings like this:

hello123
hello12324
hello12435436346

...Then I will be unable to select the number using string[:] due to differentiation in the number lengths. I hope I explained what I need clearly enough for you guys to help. Thanks!

question from:https://stackoverflow.com/questions/14471177/python-check-if-the-last-characters-in-a-string-are-numbers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
import re
m = re.search(r'd+$', string)
# if the string ends in digits m will be a Match object, or None otherwise.
if m is not None:
    print m.group()

d matches a numerical digit, d+ means match one-or-more digits (greedy: match as many consecutive as possible). And $ means match the end of the string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...