正则表达式需要某些字符串结尾

时间:2016-02-11 00:33:51

标签: python regex

我有以下三个字符串:

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

如何构建正则表达式以仅匹配第二个?我到目前为止使用的是:

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

基本上我希望它允许(1)逗号 - (2)然后是两位数 - (3)然后是字符串的结尾或空格。

3 个答案:

答案 0 :(得分:2)

假设:

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

您可以使用模式,\d\d(?: |$)

Demo

的Python:

>>> re.findall(r',\d\d(?: |$)', tgt, flags=re.M)
[',57', ',57 ']

答案 1 :(得分:1)

您已经掌握了大部分内容,但您希望确保不使用字符集[]。而是使用捕获组()。如果要获取字符串的结尾,或者空格,然后是字符串的结尾,则需要(\s$|$)。把它放在一起:r'\,\d{2}(\s$|$)'

有很多网站(如regexr.com)可以放入任何正则表达式,它会自动突出显示文本。在极少数情况下,我通常会帮助我使用正则表达式。

答案 2 :(得分: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")
相关问题