问题
What will be the regular expression in java for like this expression (3+2)+23/12-(43/54) in which left parentheses is create than user will be able to put right one and if left parentheses is not created than user will not able to put right parentheses .And if left parentheses is created 3 time than user will be able to just put right parentheses 3 times only to close the expression which is open by left parentheses.
Thanks
回答1:
In a nutshell, this is not possible using standard regular expressions.
Regular expressions can only match what's known as regular languages, and matching nested structures requires a more general type of formal language.
See Can regular expressions be used to match nested patterns?
It is, however, very easy to do what you need using other means. For example, just iterate over the string once, counting the parentheses: +1
for '('
and -1
for ')'
. At the end the count will tell you how many open parentheses there are: if the count is greater then zero, permit the user to add a closing parenthesis; otherwise, don't.
回答2:
It's not really something you can express with a regular expression.
You need a Context-Free Grammar for this.
See also here:
http://en.wikipedia.org/wiki/Context-free_grammar
under the section "Well-formed parantheses".
回答3:
Your best alternative is to use a lexer and parser. In the Java world, the favorites are ANTLR and JavaCC.
Start by modeling your calculator language in Backus-Naur Form [BNF]. Then translate into your chosen lexer, and use the parser to act on the results.
来源:https://stackoverflow.com/questions/15597745/java-scientific-calculator-regular-expression