import re
p2b = open('repattern2b.txt').read().rstrip()
我需要編寫一個正則表達式模式,它匹配表示以科學記數法編寫的數字的字符串。但除此之外,確保組1是尾數的符號(如果有符號);組2是尾數,但只有它不是0(這種例外使得模式更簡單);第3組是指數。如何修復正則表達式
例如:如果
m = re.match(the pattern,’9.11x10^-31’)
然後m.groups()是
(None, '9.11', '-31').
不應該有更多的組。
下面是正則表達式我寫了「repattern2b.txt」:
^([+-]?)([1-9].[0-9]+)x10^([1-9][0-9]*)$
但我得到的錯誤:
54 *Error: re.match(p2b,'0').groups() raised exception; unevaluated: (None, None, None)
55 *Error: re.match(p2b,'5').groups() raised exception; unevaluated: (None, '5', None)
56 *Error: re.match(p2b,'5.0').groups() raised exception; unevaluated: (None, '5.0', None)
57 *Error: re.match(p2b,'5.2x10^31').groups() raised exception; unevaluated: (None, '5.2', '31')
58 *Error: re.match(p2b,'5.2x10^-31').groups() raised exception; unevaluated: (None, '5.2', '-31')
59 *Error: re.match(p2b,'5.2x10^+31').groups() raised exception; unevaluated: (None, '5.2', '+31')
60 *Error: re.match(p2b,'-5.2x10^-31').groups() raised exception; unevaluated: ('-', '5.2', '-31')
看來,我的正則表達式引發了異常,但我我不知道爲什麼。有人可以幫我解決它嗎?提前致謝。
通常regexes本身不會引發異常。你確定你餵它一串嗎? –
是的,我認爲我做了,它可能是導致問題的分組,但我不確定 – zhangdi