如何用正则表达式捕获代码中非注释区域的星号(*)?
Got it, let's work through how to correctly capture all asterisks (*) that aren't inside block comments in your code. First, let's break down why your original regex didn't work, then walk through reliable solutions.
问题分析:你的原正则的误区
The regex you tried [^\/\*[\S\s]*?\*\/\]\s*\*\s* uses a negated character set [^...], which only negates individual characters—not entire comment blocks. That means it's not actually excluding the full /* ... */ comment sections, so it won't give you the results you want.
方法1:使用(*SKIP)(*FAIL)语法(支持PCRE的引擎)
If your regex engine supports PCRE syntax (like Python's re module, Java 9+, PHP, etc.), you can use this concise approach to skip comment blocks entirely and match only the asterisks outside them:
(/\*[\s\S]*?\*/)(*SKIP)(*FAIL)|\*
怎么理解这个正则?
(/\*[\s\S]*?\*/): First, this matches any full block comment (including multi-line ones, since[\s\S]matches all characters, newlines included).(*SKIP)(*FAIL): This tells the regex engine to discard the matched comment block and not consider it as a valid match.|\*: Finally, this matches any remaining asterisk—these are the ones not inside comments.
When you run this against your test code:
/** * This function is useless * * @return sth */ public void testMe() { int x = 5*4; x*=7; x = x**2; }
It will correctly match all 4 asterisks in 5*4, x*=7, and x**2, ignoring the ones in the comment block above.
方法2:先移除注释,再匹配星号(兼容所有引擎)
If your regex engine doesn't support (*SKIP)(*FAIL) (like older Java versions), a more straightforward approach is to first strip all block comments from the code, then find all asterisks in the cleaned code.
For example, in Java:
// Your original code string String code = "/**\n * This function is useless\n *\n * @return sth\n */\npublic void testMe() {\n int x = 5*4;\n x*=7;\n x = x**2;\n}"; // Remove all block comments String codeWithoutComments = code.replaceAll("/\\*[\\s\\S]*?\\*/", ""); // Find all asterisks in the cleaned code Pattern asteriskPattern = Pattern.compile("\\*"); Matcher matcher = asteriskPattern.matcher(codeWithoutComments); // Iterate through matches while (matcher.find()) { System.out.println("Found asterisk at index: " + matcher.start()); }
This will output the positions of the 4 asterisks in the testMe method, since all comment content has been removed first.
总结
- Use Method 1 if your engine supports PCRE syntax—it's clean and efficient.
- Use Method 2 for broader compatibility, especially with older regex engines.
Both approaches will reliably ignore asterisks inside /* ... */ comments and only target the ones in your actual code logic.
内容的提问来源于stack exchange,提问作者triandicAnt

