【发布时间】:2022-12-31 00:44:47
【问题描述】:
我正在做一些正则表达式,但我得到了这个错误:
我有这个字符串,例如"+1/(1/10)+(1/30)+1/50",我使用了这个正则表达式/\+.[^\+]*/g
它工作正常,因为它给了我['+1/(1/10)', '+(1/30)', '+1/50']
但真正的问题是当 + 位于括号内时 ()
像这样:"+1/(1+10)+(1/30)+1/50"
因为它会给['+1/(1', '+10)', '+(1/30)', '+1/50']
这不是我想要的:(...我想要的是['+1/(1+10)', '+(1/30)', '+1/50']
所以正则表达式如果看到\(.*\)就跳过它,就像它不存在一样......
如何在正则表达式中忽略?
我的代码(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),
)
【问题讨论】:
-
像这样?
\+[^+()]*(?:\([^()]*\))?regex101.com/r/3Yxr01/1
标签: javascript regex regex-lookarounds regex-negation