简体   繁体   中英

Regex for digits in end of string Python

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 ?

You can use re.findall()

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

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)

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)

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