Java Regular Expression for detecting class/interface/etc declaration

后端 未结 2 673
盖世英雄少女心
盖世英雄少女心 2021-01-25 03:39

I\'m trying to create a regular expression that detect a new class for example:

public interface IGame {

or

private class Game         


        
2条回答
  •  失恋的感觉
    2021-01-25 03:46

    Change your regex like below to match both type of string formats.

    line.matches("(?:public|protected|private|static)\\s+(?:class|interface)\\s+\\w+\\s*\\{");
    

    Example:

    String s1 = "public interface IGame {";
    String s2 = "private class Game {";
    System.out.println(s1.matches("(?:public|protected|private|static)\\s+(?:class|interface)\\s+\\w+\\s*\\{"));
    System.out.println(s2.matches("(?:public|protected|private|static)\\s+(?:class|interface)\\s+\\w+\\s*\\{"));
    

    Output:

    true
    true
    

提交回复
热议问题