subash
subash

Reputation: 3140

Java Regex to get a word from a String

How can I use a regex in java for the following?

String code = "import java.io.*;"  +
              "import java.util.*;"  +
              "public class Test1 extends Exam{" +
                  " // my code " +
              "}";

from the String above how can I get the class name Test1 exactly.

Upvotes: 1

Views: 99

Answers (1)

anubhava
anubhava

Reputation: 785316

Use this regex:

String className = code.replaceAll("(?s)^.*?(?:public|protected|private)?\\s*(?:\\s+static\\s+)?class\\s+(\\S+).*$", "$1");
//=> Test1

Upvotes: 1

Related Questions