-1

Given a source file (Java / Scala), how do I parse out the class name of the source file using Javascript?

Specifically, user enters source code into a browser-based editor. I would like to parse out the class names from the source text.

For example:

var sourceText = 

     class TestClass extends MyClass{
    // do something
    }



      class
       TestClass2
       extends
       MyParentClass2 
    {

    }

class TestClass3 
extends MyParentClass3 { }

How do I write this function:

parseClassNameFromSourceText: function (sourceText) {

} 

such that if I passed in the above source text, it will produce [TestClass, TestClass2, TestClass3]?

1 Answers1

0

You titled this "regex", but there's no way you're going to parse this out with regex. You have to write a proper (if simple) parser. Here are a few things that will trip you up:

// class Foo is imaginary
/* class Bar is just an idea */
class Baz {
  public class Quux {
    public String uhoh() { return "I am an inner class YIKES can you parse strings?!"; }
  }
}
class /* comments can go here you know! */ Bippy {}

And a few Scala-specific ones:

class Wimble {
  val `class YouMustBeJoking` = "Actually, I am a legal identifier!"
  val moreProblems = """class is always okay in strings"""
  def tricky = s"${class Glath { def iAmARealClass = true }}"
}

A full parser for Java is the subject of this question. You may be able to extend it to parse Scala well enough for these purposes (depending on what you decide about inner classes).

Community
  • 1
  • 1
Rex Kerr
  • 166,841
  • 26
  • 322
  • 407