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

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

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)

### 腾讯云 COS 怎么才能外链调用 m3u8 到别的网站播放？

Swoole · PHP开发工程师 (已认证)

As a PHP Developer

### Ubuntu搭建的WordPress如何修改php.ini？

Swoole · PHP开发工程师 (已认证)

As a PHP Developer

php新手很多不知道怎么查配置文件在哪，这里提供一个很简单的方法 使用 php -i 命令可以打印php的详细信息，可以把这堆东西输出一下 php -i > outputphp.txt，结合 grep 查找命令 php -i| grep php.ini 打印结果如下 Config...... 展开详请

### 归档存储采用的存储介质是什么, 安全可靠吗？

Swoole · PHP开发工程师 (已认证)

As a PHP Developer

### redis数据库应该怎样连接？？？

Swoole · PHP开发工程师 (已认证)

As a PHP Developer

### 如何使用holer实现从外网访问本地WEB应用？

Dingda

Dingda · 站长 (已认证)