正则表达式如何同时排除多个字符?匹配未闭合Java多行注释
Got it, let's figure out how to target only those unclosed /* ... multi-line comments in Java, while ignoring properly closed /* ... */ ones. Your initial regex \/\*(.*)[^\*\/] was on the right track but missed a key point: we need to exclude the entire */ sequence, not just individual * or / characters.
The Core Problem with Your Initial Attempt
Your regex uses [^\*\/] at the end, which only ensures the final character isn't a * or /. But this doesn't account for cases where a */ appears earlier in the comment (turning it into a closed comment), or where the comment ends with a single * or / (which still counts as unclosed). We need a way to guarantee that the entire comment block never contains the closing */ sequence.
The Solution: Use Negative Lookahead with Single-Line Mode
Here's a regex that will correctly match only unclosed multi-line comments:
(?s)\/\*(?:(?!\*\/).)*$
Let's break this down piece by piece:
(?s): Enables single-line mode (equivalent toPattern.DOTALLin Java). This makes the.character match newline characters, which is critical for handling multi-line comments that span lines.\/\*: Matches the start of a Java multi-line comment (we escape/and*because they're special regex characters).(?:(?!\*\/).)*: A non-capturing group that does the heavy lifting:(?!\*\/)is a negative lookahead that checks if the current position is not immediately followed by the closing*/sequence..matches any character (including newlines, thanks to single-line mode).- The
*repeats this check for every character in the comment, ensuring we never hit a closing*/.
$: Ensures we match all the way to the end of the string—meaning the comment never reaches a closing*/.
For Finding Unclosed Comments in a Full Code Snippet
If you're scanning a larger piece of Java code that has multiple comments (like your example with one closed and one unclosed), use this adjusted regex to target only the unclosed ones:
(?s)\/\*(?:(?!\*\/).)*?(?=$|\/\*)
The addition here is (?=$|\/\*): a positive lookahead that stops the match either at the end of the string or at the start of another /* comment. This way, it will skip over properly closed comments and only pick up the unclosed one.
Testing with Your Example
Let's test this against your sample text:
/* some comment */ /* Multi line comment start
The regex will match exactly /* Multi line comment start (the unclosed comment) and ignore the first closed one.
Key Notes for Java Implementation
When using this regex in Java code:
- Enable the
DOTALLflag instead of using(?s)inline (though both work). For example:Pattern pattern = Pattern.compile("/\\*(?:(?!\\*/).)*$", Pattern.DOTALL); - Be aware that regex isn't perfect for parsing full Java syntax (e.g., it won't handle comments inside string literals), but for simple cases of detecting unclosed multi-line comments, this works reliably.
内容的提问来源于stack exchange,提问作者Abgar Kebar

