Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

regex for ignoring character if inside () parenthesis?

I was doing some regex, but I get this bug:

I have this string for example "+1/(1/10)+(1/30)+1/50" and I used this regex /\+.[^\+]*/g

and it working fine since it gives me ['+1/(1/10)', '+(1/30)', '+1/50']

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

BUT the real problem is when the + is inside the parenthesis ()

like this: "+1/(1+10)+(1/30)+1/50"

enter image description here

because it will give ['+1/(1', '+10)', '+(1/30)', '+1/50']

which isn’t what I want :(… the thing I want is ['+1/(1+10)', '+(1/30)', '+1/50']

so the regex if it see \(.*\) skip it like it wasn’t there…

how to ignore in regex?


my code (js):

const tests = {
      correct: "1/(1/10)+(1/30)+1/50",
      wrong  : "1/(1+10)+(1/30)+1/50"
}

function getAdditionArray(string) {
      const REGEX = /\+.[^\+]*/g; // change this to ignore the () even if they have the + sign
      const firstChar = string[0];

      if (firstChar !== "-") string = "+" + string;

      return string.match(REGEX);
}

console.log(
    getAdditionArray(test.correct),
    getAdditionArray(test.wrong),
)

>Solution :

You can exclude matching parenthesis, and then optionally match (...)

\+[^+()]*(?:\([^()]*\))?

The pattern matches:

  • \+ Match a +
  • [^+()]* Match optional chars other than + ( )
  • (?: Non capture group to match as a whole part
    • \([^()]*\) Match from (...)
  • )? Close the non capture group and make it optional

See a regex101 demo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading