1

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.

3
  • will there always be extends? Commented Nov 14, 2013 at 16:36
  • 1
    You can use a captured group: /.*class (\S+) .*/ Commented Nov 14, 2013 at 16:37
  • yes may be extends or implements.. Commented Nov 14, 2013 at 16:37

1 Answer 1

1

Use this regex:

String className = code.replaceAll("(?s)^.*?(?:public|protected|private)?\\s*(?:\\s+static\\s+)?class\\s+(\\S+).*$", "$1");
//=> Test1
Sign up to request clarification or add additional context in comments.

7 Comments

(?:public|protected|private)?(?:\s+static)?\s+class
@anubhava your previous one is work. this updated one is not work.
Yes previous one was also working with your example and I had tested it.
perfect experts... thanks a lot @anubhava .. can you please explain shortly how it is work..
(?s) is for making dot match new lines. Then it matches any one of public|protected|private keywords followed by optional static and then followed by class. After that it captures \\s+ (i.e. non-space characters) and in the replacement part it replaces whole string with this captured group #1.
|

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.