Swift正则表达式适配问题:多平台函数文件特定函数集筛选求助
Hey there! Let's break down how to build the right regex for your function filtering task. I’ve dealt with similar multi-platform code cleanup before, so here’s a practical, step-by-step approach:
Before writing regex, you need to clearly define what makes your target functions distinct from the duplicates/alternatives. Ask yourself:
- Do they follow a specific naming pattern? (e.g., all start with
core_, end with_base, or lack platform-specific suffixes like_win32/_mac) - Do they have consistent return types or parameter structures?
- Are they defined in a specific syntax (C/C++, Python, etc.)?
For example, if your target functions are C-style and named like core_render()/core_update(), while duplicates are core_render_win32()/core_update_mac(), that’s your key pattern to leverage.
Let’s cover common scenarios:
Case 1: C/C++/C# Function Definitions
If you want to match only target functions without platform suffixes, use this regex:
^(\w+)\s+(core_\w+)(?!_\w{2,4})\s*\([^)]*\)\s*\{?$
Breakdown:
^: Anchors the match to the start of the line (avoids matching function calls mid-line)(\w+): Captures the return type (e.g.,void,int,float)(core_\w+): Matches your target function name (adjust the prefix to match your actual pattern)(?!_\w{2,4}): Negative lookahead to exclude functions with platform suffixes (e.g.,_win32,_macos)\s*\([^)]*\): Matches the parameter list (ignores whatever’s inside the parentheses)\s*\{?$: Accounts for optional opening braces if the function definition ends with{
Case 2: Python Function Definitions
For Python functions where you want to exclude platform-specific variants, try:
^def\s+(\w+)(?!_\w+)\s*\([^)]*\):$
Breakdown:
^def: Matches the start of a Python function definition(\w+): Captures the target function name(?!_\w+): Excludes functions with any suffix (adjust to(?!_win|_mac)for specific platforms)\s*\([^)]*\):: Matches the parameter list and closing colon
Pro tip: Use your code editor’s built-in regex search (like VS Code’s Find/Replace with regex mode) to test against your file. Try these checks:
- Does it match all your target functions?
- Does it correctly skip the duplicate/platform-specific functions?
- Adjust the regex if your functions have edge cases (e.g., hyphens in names, default parameters, multi-line definitions).
For multi-line function definitions (common in Python or formatted C code), you might need to enable "dot matches newline" mode (usually a flag like s in regex engines) to cover lines spanning multiple lines.
Once your regex is solid, you can use it to extract target functions:
- In VS Code: Use "Find All" to select all matches, then copy them to a new file.
- In command line (with
grep):grep -E '^(\w+)\s+(core_\w+)(?!_\w{2,4})\s*\([^)]*\)' your_code_file.c
内容的提问来源于stack exchange,提问作者Sal Aldana

