tags:

views:

66

answers:

4

Hello,

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?

A: 

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

Michael Goldshteyn
+2  A: 

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.

Colin Hebert
+1 (although I considered downvoting: The OP doesn't want to learn Regexps :-P )
Boldewyn
I didn't say I don't want an explanation :D
buratinas
+2  A: 

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.

alex
+1 for the m modifier
Boldewyn
+1  A: 

Have a look at How-do-I-use-a-regular-expression-to-strip-C-style-comments-from-a-file

M42