算术表达式的正则表达式 [英] Regular expression for arithmetic expression

查看:76
本文介绍了算术表达式的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个正则表达式来检查给定的字符串是否像a + b、2 + a + b、3 + 6 * 9 + 6 * 5 + a * b 等...

I,m trying to write a regex to check if the given string is like a + b, 2 + a + b, 3 + 6 * 9 + 6 * 5 + a * b, etc...

仅 + 和 * 运算符.

Only + and * operators.

我试过了

if (str.matches("(\\d|\\w \\+|\\*){1,} \\d|\\w"))

不幸的是它只处理像 3 * 7 ... (numeric * numeric) 这样的情况.

Unfortunately it only handles cases like 3 * 7 ... (numeric * numeric).

等待您的回答,感谢您阅读我.

Waiting for your answers, thanks for reading me.

推荐答案

*+ 放在字符类中.

Put * and + inside a character class.

str.matches("\\w(?:\\s[+*]\\s\\w)+");

演示

这篇关于算术表达式的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆