## 如何用正则表达式匹配数学表达式？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (98)

```a * b + c
-a * (b / 1.50)
(apple + (-0.5)) * (boy - 1)```

```--a *+ b @ 1.5.0  // two consecutive signs, two consecutive operators, invalid operator, invalid number
-a * b + 1)  // unmatched parentheses
a) * (b + c) / (d  // unmatched parentheses```

``````#!/usr/bin/perl
\$re = qr  /
(                      # start capture buffer 1
\(                  #   match an opening paren
(                   # capture buffer 2
(?:                 #   match one of:
(?>             #     don't backtrack over the inside of this group
[^()]+    #       one or more
)               #     end non backtracking group
|                   #     ... or ...
(?1)            #     recurse to opening 1 and try it again
)*                  #   0 or more times.
)                   # end of buffer 2
\)                  #   match a closing paren
)                      # end capture buffer one
/x;

sub strip {
my (\$str) = @_;
while (\$str=~/\$re/g) {
\$match=\$1; \$striped=\$2;
print "\$match\n";
strip(\$striped) if \$striped=~/\(/;
return \$striped;
}
}

while(<DATA>) {
print "start pattern: \$_";
while (/\$re/g) {
strip(\$1) ;
}
}

__DATA__
"(apple + (-0.5)) * (boy - 1)"
"((((one)two)three)four)x(one(two(three(four))))"
"a) * (b + c) / (d"
"-a * (b / 1.50)"
``````

``````start pattern: "(apple + (-0.5)) * (boy - 1)"
(apple + (-0.5))
(-0.5)
(boy - 1)
start pattern: "((((one)two)three)four)x(one(two(three(four))))"
((((one)two)three)four)
(((one)two)three)
((one)two)
(one)
(one(two(three(four))))
(two(three(four)))
(three(four))
(four)
start pattern: "a) * (b + c) / (d"
(b + c)
start pattern: "-a * (b / 1.50)"
(b / 1.50)
``````