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
| Token | Description |
|---|---|
| \/ | 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
| Input | Expected |
|---|---|
| // this is a comment | Match |
| x = 5; // inline comment | Match |
| /* block comment */ | No Match |
| no comment here | No Match |
| // TODO: fix this | Match |
Try It — Interactive Tester
Match Highlighting(3 matches)
Matches & Capture Groups
7 charsFlags: gmMatches: 3Ctrl+Shift+C to copy regex
Related Regex Patterns
Regex to Match Multi-Line Block Comments
/\/\*[\s\S]*?\*\//g
Regex to Match JavaScript Function Declarations
/function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\([^)]*\)/g
Regex to Match JavaScript Import Statements
/import\s+(?:(?:\{[^}]*\}|\*\s+as\s+\w+|\w+)\s*(?:,\s*(?:\{[^}]*\}|\*\s+as\s+\w+|\w+)\s*)*from\s+)?['"][^'"]+['"]/gm
Regex to Match HTML Comments
/<!--[\s\S]*?-->/g