1

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:

  • 25 outputs Error in 25
  • 25,25 outputs 25,25
  • 1 outputs Error in 1
  • 1,0 outputs Error in 1,0
  • 1,00 outputs 1,00
15
  • Do you need a regexp? Any reason you don't want to do text[-2:].isdigit() and text[-3] == ','? Commented Dec 17, 2015 at 16:40
  • 3
    I assume the return is meant to be indented (and the semicolon serves no purpose), but other than that, this should work. Commented Dec 17, 2015 at 16:40
  • Try this awesome online regex tester/explainer Commented Dec 17, 2015 at 16:42
  • The main reason would be that I was not aware of .isdigit(). Going to check that out. Also I fixed the indent and the semicolon. This whole Python thing is really new to me, but loving it already. Commented Dec 17, 2015 at 16:47
  • 1
    AFAICT, the code you showed is working properly. When you say that it's not matching anything, how did you verify that? Have you also verified that text is what you think it is before applying the regex? Commented Dec 17, 2015 at 16:48

2 Answers 2

2

You don't need a regex:

    text = text.strip()
    if len(text) < 3:
       return False
    if  text[-3] == "," and text[-2:].isdigit():
       # all good
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, after reviewing what .isdigit() does, my solution looks pretty similar to your code.
0

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'

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.