1

I'm trying to determine how many classes are declared in a .java file, using only that file type (can't compile and just count .class files).

I found some acceptable ways to do this, however I don't like being sloppy with anything I do. I'd like to learn how to do it more robustly, i.e. take into account fringe possibilities like this:

this is actually a block comment with class in it*/
//in line comment that contains class keyword
"string with class in it"

Regex is something very new to me, I just went through some tutorials but can't seem to find or properly articulate an expression that will match cases like these.

Would greatly appreciate any kind insight and help.
Thank you!

5
  • 4
    Unfortunately I think you're going to find regex lacking for this purpose. The correct way to do this is to write your own Java code parser or piggy back off an existing one. Commented Mar 10, 2012 at 3:14
  • 1
    Finding anonymous classes is going to be a bit tricky I think Commented Mar 10, 2012 at 3:17
  • Regexes can't handle with nested brackets; I can't believe they could handle this kind of sophisticated thing. Commented Mar 10, 2012 at 3:17
  • 1
    Also consider using the Eclipse AST stuff. Commented Mar 10, 2012 at 3:39
  • Thanks for all the insights, really appreciate it. Will look into Eclipse AST Commented Mar 10, 2012 at 5:03

2 Answers 2

2

A formal grammar describing the language would be a very exact way to do this. Better yet... you might find a grammar already written for the Java language that you could already use.

http://www.antlr.org/grammar/1152141644268/Java.g

Sign up to request clarification or add additional context in comments.

Comments

0

I think you can write regex to do this, though it may take quite a time. If you want to learn regex quickly, I recommend RegexBuddy tool. Just copy your code into tool's editor, try a regex expression and see result almost at the same time. This tool's website also provide a ton of helpful resources and snippet code of the regex language.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.