You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用正则表达式选取Java代码中x函数大括号内的代码?

Extracting Java Method Body with Regex

Got it, let's tackle this problem of pulling out the code inside the x() method's curly braces. The main challenge here is dealing with nested curly braces—basic regex won't cut it because it can't properly balance opening and closing braces. Here are two solid solutions based on what environment you're working in:

1. For PCRE-Supported Environments (Text Editors, Python, Perl, etc.)

If you're using a tool that supports PCRE (Perl Compatible Regular Expressions), you can use a recursive regex to handle nested braces. This pattern will correctly match the entire method body, even with nested blocks:

public void x\(\)\s*\{((?:[^{}]|(?R))*)\}

Breakdown of the regex:

  • public void x\(\): Matches the exact method declaration (escaping parentheses since they're special regex characters)
  • \s*: Accounts for any whitespace between the method signature and the opening brace
  • \{: Matches the opening brace of the method body
  • ((?:[^{}]|(?R))*): The capture group that grabs the method body:
    • [^{}]: Matches any character that's not a curly brace
    • (?R): Recursively matches the entire regex pattern, handling nested curly braces
  • \}: Matches the closing brace of the method body

When you run this, the first capture group will give you exactly the code you want:

if (a== null) { return;} String s = "abc"; try { if (b==1 ) { c= null; } else { d=null; } } catch (Exception e) { System.out.println(e); }

2. For Java Code (Standard Regex Engine)

Java's built-in java.util.regex doesn't support recursive regex or balance groups, so we need to combine a basic regex match with manual brace counting to find the correct closing brace. Here's how you can do it:

public class MethodExtractor {
    public static void main(String[] args) {
        String code = "public void x() { if (a== null) { return;} String s = \"abc\"; try { if (b==1 ) { c= null; } else { d=null; } } catch (Exception e) { System.out.println(e); } }";
        
        // Match the method declaration and find the start of the body
        Pattern pattern = Pattern.compile("public void x\\(\\)\\s*\\{");
        Matcher matcher = pattern.matcher(code);
        
        if (matcher.find()) {
            int startBody = matcher.end();
            int braceCount = 1;
            int endBody = -1;
            
            // Traverse the string to count braces and find the matching closing one
            for (int i = startBody; i < code.length(); i++) {
                char c = code.charAt(i);
                if (c == '{') {
                    braceCount++;
                } else if (c == '}') {
                    braceCount--;
                    if (braceCount == 0) {
                        endBody = i;
                        break;
                    }
                }
            }
            
            if (endBody != -1) {
                String methodBody = code.substring(startBody, endBody);
                System.out.println("Extracted method body:\n" + methodBody);
            }
        }
    }
}

How this works:

  1. We first locate the opening brace of the x() method using a simple regex.
  2. Then we iterate through the string starting from that point, incrementing a counter for each opening brace and decrementing for each closing brace.
  3. When the counter hits 0, we've found the matching closing brace for the method's body—this ensures we don't stop at a nested brace.

Running this code will output the exact method body you're looking for.

内容的提问来源于stack exchange,提问作者Yunus Emrah Dursun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:30:08