鱼C论坛

 找回密码
 立即注册
查看: 2988|回复: 3

[已解决]请大神帮我看下正则表达式错在哪

[复制链接]
发表于 2022-12-8 10:49:51 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
源数据
data = '"realtimemarket":null,"indexType":null,"item":["timestamp","current","high","open","low","close","chg","percent","amount","volume","avg"],"data":[["2022-11-17",2385.86,2389.46,2389.46,2351.00,2385.86,-17.05,"-0.71%",570.87,1506.53,null],["2022-11-16",2402.91,2443.79,2427.41,2399.70,2402.91,-28.82,"-1.19%",617.71,1764.51,null],["2022-11-15",2431.73,2432.46,2373.99,2356.35,2431.73,56.52,"2.38%",730.21,2037.30,null],["2022-11-08",2432.40,2460.99,2452.86,2411.72,2432.40,-22.29,"-0.91%",530.44,1345.00,null],["2022-11-07",2454.69,2470.64,2447.13,2432.05,2454.69,3.47,"0.14%",638.18,1656.64,null]]},"tota"'

想要的结果  c= ["timestamp","current","high","open","low","close","chg","percent","amount","volume","avg"]
                  v= [["2022-11-17",2385.86,2389.46,2389.46,2351.00,2385.86,-17.05,"-0.71%",570.87,1506.53,null],["2022-11-16",2402.91,2443.79,2427.41,2399.70,2402.91,-28.82,"-1.19%",617.71,1764.51,null],["2022-11-15",2431.73,2432.46,2373.99,2356.35,2431.73,56.52,"2.38%",730.21,2037.30,null],["2022-11-08",2432.40,2460.99,2452.86,2411.72,2432.40,-22.29,"-0.91%",530.44,1345.00,null],["2022-11-07",2454.69,2470.64,2447.13,2432.05,2454.69,3.47,"0.14%",638.18,1656.64,null]]

我的表达式:c  =  re.findall(r'item\":\[(.*)\],\"data',data)
                   v = re.findall(r'avg\"],\"data\":(.*)},',data)

不知道什么原因,它自动形成列表,多出这么个东西  :['']  

出来的结果是: c = ['["timestamp","current","high","open","low","close","chg","percent","amount","volume","avg"]'] ,v也同样多出个东西

请大神帮忙修改下,谢谢
最佳答案
2022-12-8 11:24:13
括号分别挪到\[和\]外就好了,另外findall返回的是列表
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-12-8 11:24:13 | 显示全部楼层    本楼为最佳答案   
括号分别挪到\[和\]外就好了,另外findall返回的是列表
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-12-8 11:28:52 | 显示全部楼层
本帖最后由 lxping 于 2022-12-8 11:34 编辑

你的表达式只能成功匹配一次,我测试了一下结果如下,输出的结果用字符串形式表示:
['"timestamp","current","high","open","low","close","chg","percent","amount","volume","avg"']
你要想以下结果,你的表达式就得匹配成功 len(c) 次:
c= ["timestamp","current","high","open","low","close","chg","percent","amount","volume","avg"]
有些时候看原始数据和你想要的结果,这种情况你用切片不是更简单么
c  =  re.findall(r'item":\[(.*)\],"data',data)
每一次匹配都会成功返回的是()里面的内容,你要成功匹配,()外的边界条件就要符合,整个字符串符合 'item\":\['  和  '\],\"data' 的就只有一个,就是下面这一整个
"timestamp","current","high","open","low","close","chg","percent","amount","volume","avg"
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2022-12-8 11:49:54 | 显示全部楼层
cflying 发表于 2022-12-8 11:24
括号分别挪到\[和\]外就好了,另外findall返回的是列表

谢谢指导!加[0]解决
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-11-15 21:08

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表