0

I have the following three strings:

>>> s_no = '¥2,571'
>>> s_yes = '$2,57'
>>> s_yes = '2,57 $'

How would I construct a regex to match only the second one? The one I am using so far is:

re.search(r'\,\d{2}[\s|$]?',s) # should start on a comma. Unconcerned what comes before it.

Basically I want it to allow a (1) comma -- (2) then two digits -- (3) then either the end of the string or a space.

0

3 Answers 3

2

Given:

>>> tgt="""\
... >>> s_no = '¥2,571
... >>> s_yes = '$2,57
... >>> s_yes = '2,57 $"""

You can use the pattern ,\d\d(?: |$)

Demo

Python:

>>> re.findall(r',\d\d(?: |$)', tgt, flags=re.M)
[',57', ',57 ']
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the answer. Could you please explain the usage of the re.M flag in the above?
re.M is for the multiline flag so that the ^ and $ regex meta characters match the beginning of logical lines versus only at the beginning and end of a string. It is only required in the example here because tgt is three logical lines and $ would only match at the very end of the string without it.
1

You've pretty much got most of it, but you want to make sure that you don't use a character set []. Instead, use a capture group (). If you want to get either the end of the string, or a space and then the end of the string, you want (\s$|$). Putting it together: r'\,\d{2}(\s$|$)'

There are plenty of websites (like regexr.com) where you can put in any regex, and it automatically highlights the text. It usually helps me out in the rare case I use regexes.

Comments

0
dollar_sign = r"\$"
dollars = r"(?P<dollars>\d+)"
cents = r"(?:,(?P<cents>\d{2}))?"
amount_re = r"^" + dollar_sign + dollars + cents + r"\s*$"

m = re.search(amount_re, "$2,57 ")

print("Got", m.group('dollars'), "dollars", end='')
print(m.group('cents') if m.group('cents') is not None else "even")

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.