Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用regex:Python在数字中插入逗号时出现问题_Python_Regex - Fatal编程技术网

使用regex:Python在数字中插入逗号时出现问题

使用regex:Python在数字中插入逗号时出现问题,python,regex,Python,Regex,我正在学习regex中的lookahead和lookahead,并尝试将逗号应用于每3位数字之间的数字。我被困在这里: text = "The population of India is 1300598526 and growing." pattern = re.compile(r'\b(?<=\d)(?=(\d\d\d)+\b)') line = re.sub(pattern, r',', text) print(line) 实际输出无。图案不匹配。我试过摆弄这个模式,发现前面的\b

我正在学习regex中的
lookahead
lookahead
,并尝试将逗号应用于每3位数字之间的数字。我被困在这里:

text = "The population of India is 1300598526 and growing."
pattern = re.compile(r'\b(?<=\d)(?=(\d\d\d)+\b)')
line = re.sub(pattern, r',', text)
print(line)
实际输出
。图案不匹配。我试过摆弄这个模式,发现前面的
\b
就是罪魁祸首。没有这个图案效果很好。为什么会这样?请澄清


我更希望知道上述模式中的错误,而不是一个新制作的模式来实现同样的效果。谢谢。

您的正则表达式以
\b(?开头,在单词边界处,如果您在后面查找一个数字,那么下面的字符不能是数字,否则就不能是单词边界。@CertainPerformance我不明白您的意思。您能用上面提到的例子更具体一点吗?
"The population of India is 1,300,598,526 and growing"
\d(?=(?:\d{3})+(?!\d))
import re

text = "The population 12test1234 of India is 1300598526 and growing."
pattern = re.compile(r"\d(?=(?:\d{3})+(?!\d))")
subst = r"\g<0>,"

res = map(lambda x: re.sub(pattern, subst, x) if re.match(r"\A\d{4,}\Z", x) else x, text.split(' '))
print (" ".join(res))
The population 12test1234 of India is 1,300,598,526 and growing.