[英]What does it mean when an error shows multiple files in a Python traceback?
[英]What does error: nothing to repeat mean in this traceback from a compiled Python regex
我有一個有趣的問題,試圖理解和改進我在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)。 但是你正在使用freespacing模式( re.VERBOSE
)。 因此,空白是微不足道的。 你的正則表達式相當於:
^*[ ]*S[iI][gG][nN][aA][Tt][uU][rR][eE][sS]?\s*[^0-9]$
即使在非原始字符串中, \\s
仍保持\\s
,因為它不是Python字符串中可識別的轉義序列。
然后在開頭^*
導致問題,因為你不能重復錨。
這就是為什么你應該總是使用原始字符串來編寫正則表達式。 然后\\t
只保留反斜杠-t,正則表達式引擎可以將其解釋為選項卡。
順便說一句, [ ]
的空格不是問題,因為即使在詳細/自由空間模式中,字符類中的空格也很重要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.