1

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

Radu Murzea
  • 10,724
  • 10
  • 47
  • 69
Hope
  • 79
  • 3
  • 14
  • 4
    You should post some code to let us help you, what have you tried? – BackSlash Mar 24 '13 at 11:15
  • i think this problem not require code because problem is in parentheses if left parentheses "(" is in expression than you can put ")" one if "(" is 3 time or more than you can put ")" 3 times or more. – Hope Mar 24 '13 at 11:20
  • 2
    It needs code, you should try to do it yourself, then come here and show us what you tried telling us what doesn't work in your code, so we can help you finding the solution – BackSlash Mar 24 '13 at 11:26

3 Answers3

4

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.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

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".

jcmikkelsen
  • 116
  • 5
  • Write a small function using a stack like this one: http://newserverside.blogspot.dk/2012/05/check-parentheses-in-string-expression.html Or write a recursive function. – jcmikkelsen Mar 24 '13 at 11:36
  • Good to hear. Please consider setting my answer as your accepted answer. Thanks. – jcmikkelsen Mar 24 '13 at 20:25
1

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.

Eric Jablow
  • 7,874
  • 2
  • 22
  • 29