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

Regex for parsing multiple conditions for groups

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

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

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

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

但我也想得到 collectionproducts

比赛的预期结果

  1. collection

  2. products

  3. take:12|skip:16

您可以拆分 .(\(.*?\))+ 上的字符串,然后使用 reduce 获取所需格式的值

const sampleString = 'collection.products(take:12|skip:16)';
const result = sampleString.split(/\.|(\(.*?\))+/).reduce((op,inp) => {
  if(inp){
    inp = inp.replace(/[)(]+/g,'')
    op.push(inp)
  }
  return op
},[])

console.log(result)

在这里,我们可以一起改变两个表达式:

(\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 可视化正则表达式:

这分你想要的。

const sampleString = 'collection.products(take:12|skip:16)';
const result = sampleString.split(/[.()]*([^.()]+)[.()]*/).filter(function (el) {return el != "";});

console.log(result)