Python 为什么正则表达式被卡住了?
我增量更新了一个正则表达式来清理数据,发现它对字符串的长度是无限长的。这是一个需要测试的Python代码Python 为什么正则表达式被卡住了?,python,regex,regex-group,re,Python,Regex,Regex Group,Re,我增量更新了一个正则表达式来清理数据,发现它对字符串的长度是无限长的。这是一个需要测试的Python代码 import re re.sub(r'(([-.]?\d+)|(\d+))+$', '', 'bcn16-01081-210300-16-20160829-ca') 我想这是因为组中重复出现了\d+,因为如果将reg exp简化为([-.]\d+\d++$,它就开始工作了。但我想知道得更准确些。任何人都知道?在([-.]?\d+)(\d+)+$中,[-.]?\d+和\d+实际上是匹配相同
import re
re.sub(r'(([-.]?\d+)|(\d+))+$', '', 'bcn16-01081-210300-16-20160829-ca')
我想这是因为组中重复出现了\d+
,因为如果将reg exp简化为([-.]\d+\d++$
,它就开始工作了。但我想知道得更准确些。任何人都知道?在([-.]?\d+)(\d+)+$
中,[-.]?\d+
和\d+
实际上是匹配相同的字符串。当在右侧应用+
时,表达式开始以类似于的方式运行
使用
[-.]?\d+(?:[-.]\d+)*$
([-.]\d+\d+$
由于嵌套的+
,仍然容易发生灾难性的回溯。请参阅有关(和)的更多信息
解释
--------------------------------------------------------------------------------
[-.]? any character of: '-', '.' (optional
(matching the most amount possible))
--------------------------------------------------------------------------------
\d+ digits (0-9) (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
(?: group, but do not capture (0 or more times
(matching the most amount possible)):
--------------------------------------------------------------------------------
[-.] any character of: '-', '.'
--------------------------------------------------------------------------------
\d+ digits (0-9) (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
)* end of grouping
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
它工作得很好。非常感谢。还感谢您讲述灾难性回溯。