bkd
bkd

Reputation: 180

How to evaluate Python Regex correctly?

There is a list of strings and I need to manipulate those which do not end in ",\d\d" (comma followed by two digits).

So I went to https://docs.python.org/2/howto/regex.html and tried out some code, put everything in my own function and out came something like this, however it doesn't match anything.

def translatePrice(text):
    text = str(text)
    text = text.strip()
    if (re.search(r',\d\d$', text) == None):
        print "Error in ", text
    return text

I am pretty sure that my regex raw string is formatted in a way that python can understand it. What I am not sure about is if the rest of the code is any good. I also found "endswith('xy')" but that doesn't help me that much since I need to match any pair of digits.

Here is some examples of how my input strings look like:

Upvotes: 1

Views: 133

Answers (2)

GingerPlusPlus
GingerPlusPlus

Reputation: 5626

it doesn't match anything.

Huh? I cannot reproduce your problem, your code works fine for me for all example input you provided:

>>> 'Good' if re.search(r',\d\d$', '25') else 'Bad'
'Bad'
>>> 'Good' if re.search(r',\d\d$', '25,25') else 'Bad'
'Good'
>>> 'Good' if re.search(r',\d\d$', '1') else 'Bad'
'Bad'
>>> 'Good' if re.search(r',\d\d$', '1,0') else 'Bad'
'Bad'
>>> 'Good' if re.search(r',\d\d$', '1,00') else 'Bad'
'Good'

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180481

You don't need a regex:

    text = text.strip()
    if len(text) < 3:
       return False
    if  text[-3] == "," and text[-2:].isdigit():
       # all good

Upvotes: 2

Related Questions