gpt4 book ai didi

python - 错误: nothing to repeat mean in this traceback from a compiled Python regex是什么意思

转载 作者:太空宇宙 更新时间:2023-11-03 13:21:08 26 4
gpt4 key购买 nike

我有一个有趣的问题正在尝试理解和改进我在 Python 中对 REGEX 的使用

这是一个正则表达式

verbose_signature_pattern_2 = re.compile("""
^ # begin match at new line
\t* # 0-or-more tab
[ ]* # 0-or-more blankspaces
S # capital S
[iI][gG][nN][aA][Tt][uU][rR][eE]
[sS]? # 0-or-1 S
\s* # 0-or-more whitespace
[^0-9] # anything but [0-9]
$ # newline character
""", re.VERBOSE|re.MULTILINE)

当我运行代码时出现错误

""", re.VERBOSE|re.MULTILINE)
File "C:\Python27\lib\re.py", line 190, in compile
return _compile(pattern, flags)
File "C:\Python27\lib\re.py", line 242, in _compile
raise error, v # invalid expression
error: nothing to repeat

如果我去掉选项卡 (\t) 特殊字符上的 0 或更多限定符,它不会抛出错误

我正在尝试查找将单词 Signature 的某些变体作为行中第一个单词的行。我知道我可以使用稍微不同的方法来获得我需要的东西。但是,我想文档的创建者可能会通过制表符使单词大致居中,或者他们可能会使用空格。我不想使用\s,因为我不想捕获可能位于带有 Signature 一词的行之前的所有空行。具体来说,我试图避免捕获所有这些垃圾

'\n\n\n\n            Signature    \n

我只想在输出中看到这个

'            Signature    \n

我确实意识到我可以轻松去除多余的换行符,但我正在尝试更准确地理解和做事。有趣的是,以下 REGEX 具有相同的开始,但它似乎按预期工作。那就是当这个编译时我没有收到错误,它似乎给了我我想要的东西——尽管我仍然需要找到更多的边缘情况。

verbose_item_pattern_2 = re.compile(r"""
^ # begin match at newline
\t* # 0-or-more tabs
[ ]* # 0-or-more blanks
I # a capital I
[tT][eE][mM] # one character from each of the three sets this allows for unknown case
\t* # 0-or-more tabs
[ ]* # 0-or-more blanks
\d{1,2} # 1-or-2 digits
[.]? # 0-or-1 literal .
\(? # 0-or-1 literal open paren
[a-e]? # 0-or-1 letter in the range a-e
\)? # 0-or-1 closing paren
.* # any number of unknown characters so we can have words and punctuation
[^0-9] # anything but [0-9]
$ # 1 newline character
""", re.VERBOSE|re.MULTILINE)

最佳答案

第一个字符串不是原始字符串。因此,当 Python 编译字符串时(在它进入正则表达式引擎之前),它会替换所有转义序列。所以 \t 实际上会变成字符串中的制表符(不是反斜杠-t)。但是您正在使用自由空间模式 (re.VERBOSE)。因此空格是微不足道的。您的正则表达式相当于:

^*[ ]*S[iI][gG][nN][aA][Tt][uU][rR][eE][sS]?\s*[^0-9]$

\s 保留为 \s,即使在非原始字符串中也是如此,因为它不是 Python 字符串中可识别的转义序列。

然后就在开头 ^* 导致了问题,因为您不能重复 anchor 。

这就是为什么您应该始终使用原始字符串来编写正则表达式的原因。然后 \t 只保留反斜杠-t,正则表达式引擎可以将其解释为制表符。

顺便说一句,[ ] 中的空格不是问题,因为即使在冗长/自由空格模式下,字符类中的空格也很重要。

关于python - 错误: nothing to repeat mean in this traceback from a compiled Python regex是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13865318/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com