简体   繁体   中英

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']

在此处输入图像描述

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

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

在此处输入图像描述

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),
)

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 .

Another option could be to be more specific about the digits and the + and / and use a character class to list the allowed characters.

\+(?:\d+[+/])?(?:\(\d+[/+]\d+\)|\d+)

See another regex101 demo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM