0

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?

eumiro
  • 207,213
  • 34
  • 299
  • 261

3 Answers3

2

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.

Community
  • 1
  • 1
Colin Hebert
  • 91,525
  • 15
  • 160
  • 151
2

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
  • 479,566
  • 201
  • 878
  • 984
0

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
  • 71,784
  • 24
  • 131
  • 181