【发布时间】:2019-05-28 10:18:52
【问题描述】:
我试图从匹配的字符串中获取 4 个连续数字。
当我尝试re.sub('[^\d]+', ',', "abc 23 [1981] ghj [5656]") 时,它会返回,23,1981,5656,。所以当我尝试re.sub('[\d]{4}+', ',', "abc 23 [2021]") 时,它会返回错误"multiple repeat at position 7"
既然我保留{4},它不应该匹配4个[\d]并返回,1981,5656,吗?
【问题讨论】:
-
print(re.findall(r"\d{4,}", s))? -
@Rakesh 这将返回
['1981', '5656']一个列表,然后我必须再次将其转换为字符串,而不是使用 regex.sub 来完成,以便它返回一个字符串 -
print(", ".join(re.findall(r"\[(\d{4})\]", s)))? -
@ShivamRaj:你不能在 Python 中量化一个量词,这就是为什么你会因为这个正则表达式
[\d]{4}+而出错。如果\d单独在其中,您也不需要将\d放入字符集中。你能清楚地说明你当前的输出和预期的输出吗? -
@PushpeshKumarRajwanshi:如果没有
+,我不会收到任何错误,而是会返回一些东西。在这样做re.sub('[^\d]+', ',', "abc 23 [1981] ghj [5656]")我得到,23,1981,5656,但我想要,1981,5656,
标签: regex python-3.x string regex-lookarounds regex-group