DevKits

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]*?\\*/")

Related patterns

Try any pattern live in the Regex Tester