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

时间:2019-06-02 15:38:48

标签: 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)

但是我也想得到collectionproducts

匹配中的预期结果

  1. collection

  2. products

  3. take:12|skip:16

3 个答案:

答案 0 :(得分:2)

您可以在.(\(.*?\))+上拆分字符串,然后使用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)

答案 1 :(得分:2)

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

(\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

RegEx电路

jex.im可视化正则表达式:

enter image description here

答案 2 :(得分:2)

这取决于您想要的内容。

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

console.log(result)