Single-Line Comments
Problem
You want to match a comment that starts with //
and runs until the end of the line.
Solution
//.*
Regex options: None |
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
Discussion
The forward slash has no special meaning in regular expressions,
so we can easily match the start of the comment with ‹//
›. Some programming languages
use forward slashes to delimit regular expressions. When you use this
regular expression in your code, you may need to escape the forward
slashes as explained in Recipe 3.1.
‹.*
› simply matches
everything up to the end of the line. We don’t need to add anything to
the regular expression to make it stop at the end of a line. Just make
sure the option “dot matches line breaks” is turned off when using this
regular expression.
See Also
Recipe 2.4 explains that the dot matches any character.
Get Regular Expressions Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.