Python 正则表达式意外结果
亲爱的,我该怎么做才能得到预期的结果 预期产出:Python 正则表达式意外结果,python,python-3.x,regex,Python,Python 3.x,Regex,亲爱的,我该怎么做才能得到预期的结果 预期产出: import re pattern =r"[1-9][0-9]{0,2}(?:,\d{3})?(?:,\d{3})?" string = '42 1,234 6,368,745 12,34,567 1234' a = re.findall(pattern,string) print(a) 实际产量: ['42', '1,234', '6,368,745'] 我试图在一本书中解决这个测验 您将如何编写一个正则表达式来匹配每三位数字中带有逗号的数
import re
pattern =r"[1-9][0-9]{0,2}(?:,\d{3})?(?:,\d{3})?"
string = '42 1,234 6,368,745 12,34,567 1234'
a = re.findall(pattern,string)
print(a)
实际产量:
['42', '1,234', '6,368,745']
我试图在一本书中解决这个测验
您将如何编写一个正则表达式来匹配每三位数字中带有逗号的数字?它必须符合以下条件:
•“42”
•“1234”
•“6368745”
但与以下情况不同:
•“12,34567”,逗号之间只有两位数字
•“1234”缺少逗号
非常感谢您的帮助 您可以使用
['42', '1,234', '6,368,745', '12', '34,567', '123', '4']
看
正则表达式详细信息
?-当前位置左侧不允许有数字或数字+,`
[1-9][0-9]{0,2}-后跟任何零、一或两位数字的非零数字
?:,\d{3}*-0次或多次出现逗号,然后出现任意三位数字
?!,?\d-当前位置右侧允许的数字为否或+位。
您可以使用以下正则表达式
import re
pattern =r"(?<!\d,)(?<!\d)[1-9][0-9]{0,2}(?:,\d{3})*(?!,?\d)"
string = '42 1,234 6,368,745 12,34,567 1234'
a = re.findall(pattern,string)
print(a) # => ['42', '1,234', '6,368,745']
您预期输出的基本原理是什么?要仅获取以逗号作为分隔符的普通数字,谢谢您的正则表达式中有什么规定您不能用逗号分隔两个不同的数字?里面有什么说他们必须被任何东西分开?有没有任何答案对你有用?
r'(?<![,\d])[1-9]\d{,2}(?:,\d{3})*(?![,\d])'
(?<! begin negative lookbehind
[,\d] match ',' or a digit
) end negative lookbehind
[1-9] match a digit other than '0'
\d{0,2} match 0-2 digits
(?: begin non-capture group
,\d{3} match ',' then 3 digits
) end non-capture group
* execute non-capture group 0+ times
(?![,\d]) previous match is not followed by ',' or a digit
(negative lookahead)