Code
Match a C-style comment
Flags: g
Match single-line (//) and multi-line (/* */) C/C++/Java/JS comments.
Pattern
Regular expression
\/\/[^\n]*|\/\*[\s\S]*?\*\/How it works
Alternation: `//` followed by any non-newline chars, OR `/*` followed by any characters (non-greedy) until `*/`. `[\s\S]` matches any char including newlines.
Matches
- ▸// TODO: refactor
- ▸/* multi\n line */
- ▸/*inline*/
Non-matches
- ▸# hash comment (not C-style)
Common gotchas
This does not handle comments inside string literals — a `//` inside a string like `"http://x"` would be matched. For robust parsing use a real tokenizer.
Language snippets
JavaScript
const re = /\/\/[^\n]*|\/\*[\s\S]*?\*\//g;Python
re.findall(r"//[^\n]*|/\*[\s\S]*?\*/", text)Go
re := regexp.MustCompile(`//[^\n]*|/\*[\s\S]*?\*/`)Java
Pattern.compile("//[^\\n]*|/\\*[\\s\\S]*?\\*/")Frequently asked questions
What is the regex for C-style comment?
The pattern \/\/[^\n]*|\/\*[\s\S]*?\*\/ (flags: g) matches C-style comment. Alternation: `//` followed by any non-newline chars, OR `/*` followed by any characters (non-greedy) until `*/`. `[\s\S]` matches any char including newlines.
What does this C-style comment pattern match?
It matches strings like // TODO: refactor, /* multi\n line */, /*inline*/, but rejects # hash comment (not C-style).
How do I use this pattern in JavaScript, Python, Go, Java?
Ready-to-run snippets are provided for JavaScript, Python, Go, Java. Copy the one for your language from the Language snippets section — each wraps the same core pattern in that language's regex API.
What are common pitfalls with a C-style comment regex?
This does not handle comments inside string literals — a `//` inside a string like `"http://x"` would be matched. For robust parsing use a real tokenizer.