[英]How to get more details from result regex javascript
Here I have a test string : 这里我有一个测试字符串:
apple 01x100 02x200 03x150
banana 01x50 02 03x10
What I want as result : 结果我想要什么:
{ "apple" : { "100":["01"], "200":["02"], "150":["03"] },
"banana" : {"50":["01"], "10":["02","03"]}
I'm trying to use regex in javascript to parse string. 我正在尝试在javascript中使用正则表达式来解析字符串。 The regex string
正则表达式字符串
/(apple|banana)((?:\s)*(?:(?:[0-9]+)(?:\s)*)*x(?:[0-9])+)+/gi
Result: 结果:
Match 1
Full match 0-26 `apple 01x100 02x200 03x150`
Group 1. 0-5 `apple`
Group 2. 19-26 ` 03x150`
Match 2
Full match 27-48 `banana 01x50 02 03x10`
Group 1. 27-33 `banana`
Group 2. 39-48 ` 02 03x10`
As you see, in Match 1 - Group 2, only 03x150 show, 01x100 and 02x200 doesn't. 如您所见,在第1场比赛-第2组中,只有03x150显示,而01x100和02x200没有显示。 In Full match it show all.
在完全匹配中显示全部。 Any idea to fix this and get the result I want ?
有什么办法解决这个问题并得到我想要的结果吗? Thanks
谢谢
I think this will work for you: 我认为这将为您工作:
const input = ` apple 01x100 02x200 03x150 banana 01x50 02 03x10 lemon 02x12 15 16 17x21 ` const parse = data => { const obj = {} const findFruits = /(\\w+)\\s+(.*)/g const findMore = /\\s*([\\d\\s]+)x(\\d+)/g let temp while (temp = findFruits.exec(data)) { const tempObj = obj[temp[1]] = {} const temp2 = temp[2] while (temp = findMore.exec(temp2)) { tempObj[temp[2]] = temp[1].split(' ') } } return obj } const out = parse(input) console.log(out)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.