【问题标题】:Quick Regex Python 3 not working快速正则表达式 Python 3 不起作用
【发布时间】:2013-09-03 09:37:42
【问题描述】:
if re.findall(r"i am .*", a):
    reg = re.compile(r" i am ([\w]+).*?$")
    print('How long have you been {}?'.format(*reg.findall(a)))

所以如果我输入:

i am struggling with life...

它应该输出:

How long have you been struggling?

但由于某种原因,我得到了一个元组错误?

顺便说一句,a 只是一个输入字段。

Traceback (most recent call last):
  File "program.py", line 14, in <module>
    print('How long have you been {}?'.format(*reg.findall(a)))
IndexError: tuple index out of range

【问题讨论】:

    标签: python regex python-3.x tuples


    【解决方案1】:

    您的第二个正则表达式不匹配:

    re.compile(r" i am ([\w]+).*?$")
    

    因为它以空格开头。删除该初始空间,它可以正常工作:

    >>> a = 'i am struggling with life...'
    >>> reg = re.compile(r" i am ([\w]+).*?$")
    >>> reg.findall(a)
    []
    >>> reg = re.compile(r"i am ([\w]+).*?$")
    >>> reg.findall(a)
    ['struggling']
    

    您看到的异常被抛出,因为 .format() 方法接收位置参数作为元组,尝试查找项目 0,并且当它被传递了一个 empty 参数集时,您会得到 @987654324 @。

    【讨论】:

    • 还有一件事...... @Martijn Pieters 我如何让 Pi am 这样的字符串不出现?就像我希望 Pi 不注册一样。
    • 使用^\A将正则表达式锚定到字符串的开头,或者使用re.match()只查看字符串的开头。
    • 好的,谢谢@Martjin Pieters,但我不是指字符串的开头。就像它可能是这样的:你惹恼了我,所以我很沮丧。我希望它返回沮丧。我可以做一个陈述吗?我想是这样的:[^| ]
    • @NoviceProgrammer:然后使用\b 锚定单词边界。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    • 2014-12-03
    • 2011-05-16
    • 2016-01-15
    • 2011-12-24
    • 1970-01-01
    • 2021-06-10
    相关资源
    最近更新 更多