xMutzelx
xMutzelx

Reputation: 586

regex replace single line c++ comments

I would like to insert doxygen comments into my project. I want to do this as automatic as possible, so I had the idea to use regex and the search and replace functionality.
Example:

int var; //Explanation variable

into:

int var; /**< @brief Explanation variable */

As a bonus, I also don't want to delete my code intend.
I tried different things like

Find: .+;*// .+ (finds the relevant lines)
Replace: .+;*/**< @brief .+ */

Problem is, that it doesn't insert the original text, it inserts the regex as plain text and it deletes the code intend. Is there a way to to this properly? I have read many different posts but I can't get it working.

Upvotes: 1

Views: 571

Answers (3)

xMutzelx
xMutzelx

Reputation: 586

I modified the solution of @WiktorStribizew a bit, to make it even more comfortable:

Find: (.+;[^\r\n]\s*)//\s*([^\r\n]+)

I inserted [^\r\n] into the front, to avoid some special cases like:

int var;
//Comment for the next function
int function ()

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626754

You need to use capturing groups and backreferences:

Find what: (.+;\s*)//\s*([^\r\n]+)
Replace with: $1/**< @brief $2 */

See the regex demo.

Details:

  • (.+;\s*) - Group 1 (its value is accessed with the $1 numbered backreference from the replacement pattern): any one or more chars other than line break chars, ; and then 0+ whitespaces
  • // - a double /
  • \s* - 0+ whitespaces
  • ([^\r\n]+) - Group 2 (its value is accessed with the $2 numbered backreference from the replacement pattern): any 1+ chars other than newline (\n) and carriage return (\r) chars (as . matches a CR (\r) in .NET regex).

VS 2015 test: enter image description here

Upvotes: 1

Mustofa Rizwan
Mustofa Rizwan

Reputation: 10466

You can try this:

^(\s*[^;]+;\s*)\/\/(.*)$

and replace by this:

$1/**< @brief $2 */

Regex101Demo

Upvotes: 1

Related Questions