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

使用Python正则表达式提取代码中的函数

Fixing Regex to Extract All Function Calls/Definitions

Your current regex runs into two key issues: greedy matching that captures overly broad chunks of code, and an inability to handle nested parentheses or string literals. Let's break down how to fix this.

Why Your Current Regex Fails

  • The .* in your pattern is greedy—it grabs everything from the first ( to the very last ) in the entire string, leading to matches like main() { printf("hello to all the good people"); printf("hello to all the good people %d ", GetLastError() instead of isolating individual functions.
  • It doesn’t account for nested parentheses (e.g., GetLastError() inside printf(...)), so it cuts off incomplete function calls.
  • It ignores parentheses inside string literals, which could break matches if your code has strings containing ( or ).

A Robust Solution with Recursive Regex

To handle nested functions and string literals, we’ll use a recursive regex (supported in Python’s re module) that properly identifies the boundaries of each function call/definition. We’ll also add a recursive helper function to capture nested functions inside arguments.

import re

def extract_all_functions(content):
    # Regex pattern to match valid function calls/definitions
    func_pattern = re.compile(r'''
        \b                  # Word boundary to avoid partial identifier matches
        [a-zA-Z_]\w*        # Valid function name (starts with letter/underscore)
        \s*                 # Optional whitespace before opening parenthesis
        \(                  # Opening parenthesis
        (?:                 # Non-capturing group for argument content
            "(?:\\.|[^"])*" # Match string literals (handles escaped quotes)
            |               # OR
            (?R)            # Recursively match nested function calls
            |               # OR
            [^()"]+         # Match any characters except () and "
        )*                  # Repeat for all argument content
        \)                  # Closing parenthesis
    ''', re.VERBOSE)
    
    matches = []
    # Find all top-level function matches
    for match in func_pattern.finditer(content):
        func_str = match.group()
        matches.append(func_str)
        # Recursively search inside the function's arguments for nested functions
        args_content = func_str[func_str.index('(')+1:-1]
        matches.extend(extract_all_functions(args_content))
    
    return matches

# Your test content
content = 'int main() { printf("hello to all the good people"); printf("hello to all the good people %d ", GetLastError()); for(int i =0; i<15; i++) { if(i == 5) { switch(i) { case 0: break; } } } }'

# Extract and print all functions
all_functions = extract_all_functions(content)
for func in all_functions:
    print(func)

What This Does

  • Recursive Pattern: The (?R) syntax lets the regex match nested function calls inside arguments (like GetLastError() inside printf(...)).
  • String Handling: The "(\.|[^"])*" segment skips over string literals, ensuring parentheses inside quotes don’t break the match.
  • Nested Extraction: The helper function not only captures top-level functions but also digs into each function’s arguments to find nested calls.

Expected Output

Running this code on your test content will output:

main()
printf("hello to all the good people")
printf("hello to all the good people %d ", GetLastError())
GetLastError()

Caveats

Regex isn’t a full parser for C-like languages—it won’t handle every edge case (e.g., preprocessor directives, comments with parentheses). But for most standard function calls and definitions, this approach works reliably.

内容的提问来源于stack exchange,提问作者Yoram Abargel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:54:14