How to match a method block using regex?

前端 未结 7 1295
孤街浪徒
孤街浪徒 2021-01-06 10:06

Take an example.

 public static FieldsConfig getFieldsConfig(){
    if(xxx) {
      sssss;
    }
   return;
}

I write a regex, \"\\\\

7条回答
  •  悲&欢浪女
    2021-01-06 10:37

    Try this

    ((?\h+)public\s+static\s+[^(]+\([^)]*?\)\s*\{.*?\k\})|(public\s+static\s+[^(]+\([^)]*?\)\s*\{.*?\n\})
    

    Explanation:
    We will capture method block start by keyword public end to }, public and } must have the same \s character so your code must be well format : ) https://en.wikipedia.org/wiki/Indent_style

    \h: match whitespace but not newlines
    (?\h+): Get all whitespace before public then group in space name
    public\s+static\s public static
    [^(]: any character but not (
    ([^)]: any but not )
    \k\}: } same number of whitespace then } at the end.

    Demo

    Input:

    public static FieldsConfig getFieldsConfig(){
        if(xxx) {
          sssss;
        }
       return;
    }
    
    NO CAPTURE
    
    public static FieldsConfig getFieldsConfig2(){
        if(xxx) {
          sssss;
        }
       return;
    }
    
    NO CAPTURE
    
        public static FieldsConfig getFieldsConfig3(){
            if(xxx) {
              sssss;
            }
           return;
        }
    
    NO CAPTURE
    
            public static FieldsConfig getFieldsConfig4(){
                if(xxx) {
                  sssss;
                }
               return;
            }
    

    Output:

    MATCH 1
    3.  [0-91]  `public static FieldsConfig getFieldsConfig(){
        if(xxx) {
          sssss;
        }
       return;
    }`
    
    MATCH 2
    3.  [105-197]   `public static FieldsConfig getFieldsConfig2(){
        if(xxx) {
          sssss;
        }
       return;
    }`
    
    MATCH 3
    1.  [211-309]   `   public static FieldsConfig getFieldsConfig3(){
            if(xxx) {
              sssss;
            }
           return;
        }`
    
    MATCH 4
    1.  [324-428]   `       public static FieldsConfig getFieldsConfig4(){
                if(xxx) {
                  sssss;
                }
               return;
            }`
    

提交回复
热议问题