Regex to Match Single-Line Comments

Match single-line comments starting with // in JavaScript, TypeScript, C, C++, Java, and similar languages. Free online regex pattern tester.

Regular Expression

/\/\/.*$/gm

Token Breakdown

TokenDescription
\/Matches a literal forward slash
\/Matches a literal forward slash
.Matches any character except newline (unless dotAll flag is set)
*Matches the preceding element zero or more times (greedy)
$Anchors at the end of the string (or line in multiline mode)

Detailed Explanation

This regex matches single-line comments that use the double-slash syntax common in C-style programming languages. Here is the token-by-token breakdown:

// — Matches two literal forward slashes that mark the beginning of a single-line comment. Each forward slash is escaped with a backslash. While forward slashes do not strictly need escaping in all regex contexts, escaping them is a common convention especially when the regex is delimited by forward slashes in languages like JavaScript.

.* — Matches zero or more of any character except newline. The dot matches any character and the asterisk quantifier allows zero or more repetitions. This captures the entire comment text following the double slash, from the first character after // to the end of the line.

$ — Anchors the match at the end of a line. Combined with the m (multiline) flag, this matches the end of each line rather than only the end of the entire string.

The g flag enables global matching to find all comments in the source code. The m flag enables multiline mode so that $ matches at each line ending, not just the end of the string. This is essential for processing multi-line source code files.

This pattern is widely used in code analysis, syntax highlighting, comment stripping, and documentation extraction. Note that it will also match URLs containing // if they appear outside of string literals. For production use in a code parser, additional logic is needed to skip matches inside string literals.

Example Test Strings

InputExpected
// this is a commentMatch
x = 5; // inline commentMatch
/* block comment */No Match
no comment hereNo Match
// TODO: fix thisMatch

Try It — Interactive Tester

//gm
gimsuy

Match Highlighting(3 matches)

// this is a comment x = 5; // inline comment /* block comment */ no comment here // TODO: fix this

Matches & Capture Groups

#1// this is a commentindex 0
#2// inline commentindex 28
#3// TODO: fix thisindex 82
Pattern: 7 charsFlags: gmMatches: 3

Ctrl+Shift+C to copy regex

Customize this pattern →