python求一个的正则表达式,最好不用零宽断言,感谢,题如下

20.如何写一个正则表达式,匹配每 3 位就有一个逗号的数字?它必须匹配以
下数字:
 '42'
 '1,234'
 '6,368,745'
但不会匹配:
 '12,34,567' (逗号之间只有两位数字)
 '1234' (缺少逗号)
最新回答
输了却不死心

2024-11-25 11:57:15

Python正则表达式  \d{1,3}(,\d{3})*$

完整的Python程序如下

#!/usr/bin/python 

import re

str = '6,368,745'

regex = r'\d{1,3}(,\d{3})*$'

match_obj = re.match(regex,str)

if match_obj:

 print('true')

else:

 print('false')



运行结果
true
追问
import re
num=re.compile(r"\d{1,3}(,\d{3})*$")
print(num.findall("1,234,567"))
—>[',567']
你好,为什么移植你的正则表达式后,用findall函数无法正常匹配,源码在上,麻烦了
追答

如果你用findall函数,需要把\d{1,3}(,\d{3})*作为一个捕获组括起来r"(\d{1,3}(,\d{3})*)$"

完整的Python程序如下

#!/usr/bin/python 

import re

num=re.compile(r"(\d{1,3}(,\d{3})*)$")

print(num.findall("1,234,567"))


运行结果
[('1,234,567', ',567')]