我正在尝试使用正则表达式将字符串拆分为 3 个不同的部分。
我只能从字符串中获取函数参数,但我也想获取字符串的其他部分
const regex = /(\(.*?\))+/g;
const sampleString = 'collection.products(take:12|skip:16)';
const result = sampleString.match(regex)
它给了我(take:12|skip:16)
但我也想获得收藏
和产品
比赛预期结果
集合
产品
取:12|跳过:16
最佳答案
在这里,我们可以一起改变两个表达式:
(\w+)|\((.+?)\)
第 1 组将捕获我们想要的单词 (\w+)
,第 2 组将捕获括号中所需的输出。
const regex = /(\w+)|\((.+?)\)/gm;
const str = `collection.products(take:12|skip:16)`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Demo
正则表达式电路
jex.im可视化正则表达式:
关于javascript - 用于解析组的多个条件的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56416505/