简体   繁体   中英

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.

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

-b+a+ab

That I do not want as b is not specified as a variable. 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)+)*$

See demo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM