[英]JavaScript String split with multiple delimiters while keeping the delimiters
I want to split a string in JavaScript using multiple delimiters while still keeping the delimiters. 我想使用多个定界符在JavaScript中拆分字符串,同时仍保留定界符。 I tried it with this RegEx but I get matches I'm not interested in.
我用此RegEx尝试过,但是得到了我不感兴趣的比赛。
"id:123 name:test pumpe desc:pumpe p123".split(/(?=(id:))|(?=(name:))|(?=(desc:))/gi)
The Output I get: 我得到的输出:
["id:123 ", undefined, "name:", undefined, "name:test pumpe ", undefined, undefined, "desc:", "desc:pumpe p123"]
The Output I want: 我想要的输出:
["id:123", "name:test pumpe", "desc:pumpe p123"]
I tried plaing a bit with the regex but couldn't get my desired output. 我用正则表达式尝试了一下,但没有得到想要的输出。
The delimiters you actually want to split by are spaces, specifically, spaces that are followed by name:
, id:
or desc:
. 您实际要分割的定界符是空格,特别是后面跟有
name:
, id:
或desc:
空格。
Following this logic, this regex can be constructed: 按照此逻辑,可以构造此正则表达式:
/ (?=name:|id:|desc)/i
(Note the initial space) (注意初始空间)
Try it here: https://regex101.com/r/0RxEU9/1 在这里尝试: https : //regex101.com/r/0RxEU9/1
console.log("id:123 name:test pumpe desc:pumpe p123".split(/ (?=name:|id:|desc)/i))
您可以查找空格,而不要查找空格和冒号。
console.log("id:123 name:test pumpe desc:pumpe p123".split(/\\s(?=\\S+?:)/));
If the key names are unknown you could do split
at every \\s
which is followed by \\w+:
如果键名未知,则可以在每个
\\s
处进行split
,然后再跟\\w+:
( Regex demo ) (正则表达式演示 )
const splits = "id:123 name:test pumpe desc:pumpe p123".split(/\\s+(?=\\w+:)/) console.log(splits)
您正在寻找遵循[name:]|[desc:]|[id:]
模式的任何内容,因此简化了您的正则表达式:
console.log("id:123 name:test pumpe desc:pumpe p123".split(/ (?=name:|id:|desc:)/i));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.