Taha Ergun
Taha Ergun

Reputation: 616

Regex for parsing multiple conditions for groups

I am trying to split string in 3 different parts with regex.

I can only get function parameters from string but i also want to other parts of the string

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

It gives me (take:12|skip:16)

But i also want to get collection and products

Expected result in match

  1. collection

  2. products

  3. take:12|skip:16

Upvotes: 2

Views: 739

Answers (3)

user557597
user557597

Reputation:

This splits on what you want.

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

console.log(result)

Upvotes: 1

Emma
Emma

Reputation: 27723

Here, we can alter two expressions together:

(\w+)|\((.+?)\)

which group #1 would capture our desired words (\w+) and group #2 would capture the desired output in the brackets.

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 Circuit

jex.im visualizes regular expressions:

enter image description here

Upvotes: 2

Code Maniac
Code Maniac

Reputation: 37755

You can split the string on . and (\(.*?\))+ and then use reduce to get values in desired format

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)

Upvotes: 1

Related Questions