如何正确计算Python正则表达式?

2024-04-26 18:05:47 发布

您现在位置:Python中文网/ 问答频道 /正文

有一个字符串列表,我需要处理那些不以“,\d\d”(逗号后跟两位数字)结尾的字符串。你知道吗

所以我去https://docs.python.org/2/howto/regex.html尝试了一些代码,把所有的东西都放在我自己的函数中,结果是这样的,但是它与任何东西都不匹配。你知道吗

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

我非常确定我的regex原始字符串的格式是python可以理解的。我不确定的是剩下的代码是否好。我还找到了“endswith('xy')”,但这对我帮助不大,因为我需要匹配任何一对数字。你知道吗

下面是一些输入字符串的示例:

  • 25输出Error in 25
  • 25,25输出25,25
  • 1输出Error in 1
  • 1,0输出Error in 1,0
  • 1,00输出1,00

Tags: 字符串代码textinhttpsorgdocs列表
2条回答

你不需要正则表达式:

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

it doesn't match anything.

嗯?我无法重现您的问题,对于您提供的所有示例输入,您的代码对我来说都很好:

>>> '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'

相关问题 更多 >