0

I want to get boolean for all strings having digits at the end of string. For example

import re
# list of strings
li = ['/Usein-kysytyt-kysymykset;jsessionid=0727CD5A45A05D3CBD5A26D459C34D9D.xxlapp11',
      '/vaatteet/naisten-vaatteet/naisten-takit/c/120204',
      '/pyoraily/pyorailyvarusteet/pyorankuljetuslaukut-ja-vannepussit/c/100818_8']
for i in li:
    if(bool(re.match('\d+$', i))):
        print(i)

So this should work and return me True for li[1] and li[2] and False for li[0] but it is returning false for all elements in the list. What is wrong here ?

4
  • 6
    re.match only matches at the beginning of a string. Use re.search instead! Commented May 1, 2017 at 15:05
  • re.match should do the trick, but in li I see that all strings end with digits so it should return all of them. Commented May 1, 2017 at 15:07
  • 1
    Wouldnt you expect li[0] to be True also since it ends with 11? Commented May 1, 2017 at 15:24
  • Yes it'll be True as well. I thought it was alphabet. Commented May 1, 2017 at 16:22

3 Answers 3

1

You can use re.findall()

for i in li:
    if(bool(re.findall('\d+$', i))):
        print(i)
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

for i in li:
#get last occurrence of that string
    l = i[len(i) - 1]
    #if it is a number then do following
    if l.isdigit():
        print(i)

Comments

1

The python docs about re.match:

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance.

To find out if the last element of a string is a digit, use this instead:

for i in li:
    if(bool(re.search(r'\d+$', i))):
        print(i)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.