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),
)
CodePudding user response:
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.