这里我有一个测试字符串:
apple 01x100 02x200 03x150
banana 01x50 02 03x10
我想要的结果是:
{ "apple" : { "100":["01"], "200":["02"], "150":["03"] },
"banana" : {"50":["01"], "10":["02","03"]}
我正在尝试在javascript中使用正则表达式来解析字符串。正则表达式字符串
/(apple|banana)((?:\s)*(?:(?:[0-9]+)(?:\s)*)*x(?:[0-9])+)+/gi
结果:
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`
如您所见,在第1组 - 第2组中,只有03x150显示,01x100和02x200没有。在完全匹配中它显示所有。有任何想法来解决这个问题并获得我想要的结果吗?感谢
答案 0 :(得分:0)
我认为这对你有用:
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)