简单算术字符串的正则表达式 [英] Regular Expression for Simple Arithmetic String
问题描述
我正在尝试验证一个简单的算术表达式,以确保它适合格式操作数运算符操作数:234.34 + 5.我想出了如何足够简单地验证这一点,但我希望用户能够继续输入更多超过2个值,如:234.34 + 5/6 * 7 - -34。到目前为止,我的正则表达式如下:
I'm trying to validate a simple arithmetic expression to insure it fits within the format operand operator operand : 234.34 + 5. I figured out how to validate this easy enough, but I want the users to be able to continue inputting more than 2 values such as: 234.34 + 5 / 6 * 7 - -34. So far my regex is as follows:
[-]*\d+[.\d+[E\d+]*]*[\s+[*+/-]\s+[-]*\d+[.\d+[E\d+]*]*]*
这部分有效,但我遇到的问题是它允许我不想要的一些奇怪的东西,如-4.34.1 - 34 +
This partially works, but the problem I have is it allows for some strange things I don't want such as -4.34.1 - 34 +
有什么建议吗?
推荐答案
试试这个。这很丑陋但它应该有用(如果你没有使用任何括号):
Try this. It's ugly as hell but it should work (if you aren't using any parentheses):
-?\d+(?:\.\d+(?:E\d+)?)?(\s*[-+/\*]\s+-?\d+(?:\.\d+(?:E\d+)?)?)+
解释
这将算一个数字后跟一个运算符和一个数字无限期
This will math a number followed by an operator and a number indefinitely
-
- ?\\ \ +(?:\。\\\ +(?:E \ d +)?)?
匹配一个数字 -
(
-
\ * *
可选空格 -
[ - + / \ *]
任何运算符:+
,-
,*
,/
-
\s +
至少一个空格(以避免--b) -
- ?\d +(?:\ 。\ + +(?:E \ d +)?)?
匹配另一个号码
-?\d+(?:\.\d+(?:E\d+)?)?
Match a number(
\s*
optional whitespace[-+/\*]
any operator:+
,-
,*
,/
\s+
at least one whitespace (to avoid a --b)-?\d+(?:\.\d+(?:E\d+)?)?
match another number
数字表达式:
-
- ?
可选-
-
\d +
数字(一个或多个) -
(?:
start可选部分
-
\。
dot -
\d +
数字 -
(?:
可选科学记数法部分的开头
- E匹配
E
char -
\d +
匹配digitx
-?
optional-
\d+
digits (one or more)(?:
start of optional part\.
dot\d+
digits(?:
start of optional scientific notation part- E match
E
char \d+
match digitx
但我强烈建议尝试为此编写一个合适的解析器,它还允许支持括号:
a +(b + c)
。But i strongly suggest trying to write a proper parser for this, it will also allow supporting of parentheses:
a + (b + c)
.这篇关于简单算术字符串的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- E match
- E匹配
-
-