skip to Main Content

"So happy with the performance of this object (Review 30, 2, 1)"

Desired Output: [‘(Review 30, 2, 1)’, 30, 2, 1]

"So happy with the performance of this object (Review 30)"

Desired Output: [‘(Review 30)’, 30]

I am trying to get above desired output using regex but I am unable to get desired result.

  1. I want to get string inside parenthesis as well as all numbers inside parenthesis.

  2. I want to get parenthesis removed from string and get remaining string.

Desired output: "So happy with the performance of this object"

console.log("So happy with the performance of this object (Review 30, 2, 1)".match(/((.*?))/)[0].match(/([([0-9]+))/));

2

Answers


  1. If you want to get your output in a single match operation then use:

    const arr = ['So happy with the performance of this object (Review 30, 2, 1)',
               'So happy with the performance of this object (Review 50)'];
    const re= /(?<=(Reviews+(?:d+,s*)*)d+(?=(?:,s*d+)*))/g;
    
    arr.forEach( el => {
      var res = [el];
      [...el.matchAll(re)].forEach(m => res.push(m[0]))
      console.log(res);
    });

    Output:

    ["So happy with the performance of this object (Review 30, 2, 1)", "30", "2", "1"]
    ["So happy with the performance of this object (Review 50)", "50"]
    

    RegEx Demo

    RegEx Demo:

    • (?<=(Reviews+(?:d+,s*)*): Lookbehind to assert that we have Review then 1+ whitespace then 0 or more digits separated by comma before current position
    • d+: Match 1+ digits
    • (?=(?:,s*d+)*)): Lookahead to assert that we have 0 or more digits separated by comma and ending with a | after the current position
    Login or Signup to reply.
  2. You have a closing parenthesis in your second regex ([([0-9]+)) You can see what it matches here https://regex101.com/r/NoWt7G/1

    Apart from that, you can remove the opening parenthesis from the character class as well as the surrounding capture group. Also you have to use the /g flag to get all matches.

    What you might do it make use of a callback to match all numbers in the match for the parenthesis with d+ or with word boundaries to prevent partial word matches bd+b

    [
      "So happy with the performance of this object (Review 30, 2, 1)",
      "So happy with the performance of this object (Review 30)"
    ].forEach(s => {
      let parts = [];
      const replaced = s.replace(/([^()]*)/g, m => {
        parts.push(m);
        parts = parts.concat(m.match(/bd+b/g))
        return "";
      });
      console.log(replaced);
      console.log(parts);
    })

    Note if there has to be at least a single digit present in the match, you can change the regex to

    ([^()d]*d[^()]*)
    

    See a regex demo.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search