javascript - 用于解析组的多个条件的正则表达式

标签 javascript regex regex-lookarounds regex-group regex-greedy

我正在尝试使用正则表达式将字符串拆分为 3 个不同的部分。

我只能从字符串中获取函数参数,但我也想获取字符串的其他部分

const regex = /(\(.*?\))+/g;
const sampleString = 'collection.products(take:12|skip:16)';
const result = sampleString.match(regex)

它给了我(take:12|skip:16)

但我也想获得收藏产品

比赛预期结果

  1. 集合

  2. 产品

  3. 取: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可视化正则表达式:

enter image description here

关于javascript - 用于解析组的多个条件的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56416505/

相关文章:

javascript - 如何使 `winston` 日志库像 `console.log` 一样工作?

javascript - jQuery keyup 函数不起作用?

C# 正则表达式匹配括号内的任何内容

正则表达式匹配文件名中的字符串,同时排除另一个字符串

javascript - jQuery 没有选择 Bootstrap 按钮

Javascript(纯)选择第一个元素(表)

javascript - jquery 封装电子邮件地址

python - 在 python 中使用正则表达式排除模式

regex - 不包含特定字符串的正则表达式

python正则表达式向前看正+负