I don't want to learn regexps only for this particular problem. I need to find some '/*N*/ ' comments through C++ files. Can someone write a regexp which finds such comments?
-
You do want or don't want RegExp? – kennytm Oct 14 '10 at 14:06
-
don't want to learn :) sorry for that mistake – Oct 14 '10 at 14:06
-
Are you literally looking for N, or is N the actual comment text? – onaclov2000 Oct 14 '10 at 14:09
-
`\/\*N\*\/` - and don't tag the question with `c++` if it is actually a `regex` problem... – eumiro Oct 14 '10 at 14:10
-
possible duplicate of [Python snippet to remove C and C++ comments](http://stackoverflow.com/questions/241327/python-snippet-to-remove-c-and-c-comments) – kennytm Oct 14 '10 at 14:10
-
@KennyTM -1: yes, everyone has python installed and already knows what a hell scripts are – Oct 14 '10 at 18:06
3 Answers
Try this regex :
/\/\*(.*?)\*\//
This is how it works :
\/ <- The / character (escaped because I used / as a delimiter)
\* <- The * character (escaped because it's a special character)
( <- Start of a group
. <- Any character
* <- Repeated but not mandatory
? <- Lazy matching
) <- End of the group
\* <- The * character
\/ <- The / character
Edit : It doesn't handle \n
nor \r\n
, if you want it to then consider @Alex answer with the m
flag.

- 1
- 1

- 91,525
- 15
- 160
- 151
-
+1 (although I considered downvoting: The OP doesn't want to learn Regexps :-P ) – Boldewyn Oct 14 '10 at 14:12
-
What about
/\/\*(.+?)\*\//m
$1
will be your comments.
Hopefully m
pattern modifier will make the period (match all) match new lines (\n
) as well.
Note the +
means it will only match comments with at least one character - since it seems you want to know the comments themselves, this is OK (what use will 0 length comment be)?
However, if you want to know the total comment blocks, change the +
(1 or more) to *
(0 or more).
Also, why not give regex a try? It is tricky at the start because the syntax looks funny, but they are really powerful.

- 479,566
- 201
- 878
- 984
How about: (?<=\/*)(.*?)(?=*\/)
Which uses lookbehinds and lookaheads and captures the comment text (otherwise remove the parens around the .*, not to capture). Make sure you use a multi-line search, because these are multi-line comments

- 71,784
- 24
- 131
- 181