[英]Capturing variables with Regular Expression in java
I have been trying to capture specified variables in a program which will also evaluate the validity of simple mathematical expression. 我一直试图在程序中捕获指定的变量,该程序还将评估简单数学表达式的有效性。
Assuming the variable declared are a and bc. 假设声明的变量是a和bc。
I came up with something like this 我想出了这样的东西
^[+-][(a)(bc)]+[(a)(bc)]*+([+-x/][(a)(bc)]+[(a)(bc)]*)*$
My intention is to validate expressions like 我的目的是验证像
+a-bc-a
-bc+a-a
But it seems this expression also returns true for 但似乎此表达式也返回true
-b+a+ab
That I do not want as b is not specified as a variable. 我不希望因为b未指定为变量。 Any help would really be appreciated.
任何帮助将不胜感激。
^[+-](?:(a)|(bc))+(?:(a)|(bc))*+(?:[+-x\/](?:(a)|(bc))+(?:(a)|(bc))*)*$
[]
is a character class and matches a single character, not alternation. []
是字符类,并且匹配单个字符,而不是交替字符。 Also your regex suffers from catastrophic backtracking. 您的正则表达式也遭受灾难性的回溯。 See demo.
参见演示。
You can also reduce it to 您也可以将其减少为
^[+-](?:a|bc)+(?:[+-x\/](?:a|bc)+)*$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.