Search code examples
javaregexcompiler-theorylanguage-theory

programming a "compiler" - any way of knowing if a { (opener) was } (closed)?


Ok, so, I have an exercise to build a sort of a java compiler. I won't get too much in details. Basically, I want to know if it's possible to use a regex that can identify a closing bracket. for example, this would be a legal input

void foo(){
   asd
}

and this won't be

void foo(){
   asd
   if (){
      asd
   }

as you can see, there is only 1 closer (}) for 2 openers ({), making it invalid input. is there any way to use a regex and identify that the number of appearances matches?


Solution

  • It is not possible to check for correct parentheses with regular expressions, because to check that you'd need to track how many brackets have been opened etc, but regular expressions cannot do that.

    I suggest to you, especially if you want to construct a compiler, to familiarize yourself with formal language theory. For example, this wikipedia article gives some insight on regular expressions in the context for formal language theory: http://en.wikipedia.org/wiki/Regular_expression#Formal_language_theory