Page 1 of 1

Stumped over this one

Posted: Mon Nov 08, 2021 5:38 pm
by terrypin
I've been trying various regex expressions but so far in vain.

How do I change lines like this:
/*Set volume to 20*/

to this:
// Set volume to 20

IOW replace '/*' by '// ' (note the space), and delete '*/'

Posted: Mon Nov 08, 2021 5:51 pm
by ben_josephs
Find what: ^/\*(.*)\*/
Replace with: // $1

Posted: Mon Nov 08, 2021 6:03 pm
by terrypin
Thanks! Saw your impressively fast reply as I was coming back to proudly present the solution I came up with:

Code: Select all

Find what: (/*)(.*)(*/)
  Replace with: // 2
Seemed to work on first tests. Does that look reliable?

Posted: Mon Nov 08, 2021 10:27 pm
by ben_josephs
There's a bug in the current version of the software that runs these forums. Single backslashes in posts get swallowed, so you have to double them. Your example should look like this:

Code: Select all

Find what: (/\*)(.*)(\*/)
Replace with: // \2
Yes, that works. But the first and third pairs of parentheses unnecessarily capture text that is discarded. Also, unlike the version I gave, it captures comments that aren't at the beginning of a line.

And in a TextPad replacement expression \2 means the same as $2 .

Posted: Tue Nov 09, 2021 9:37 am
by terrypin
Indeed, quite a bug for discussions about regex! Particularly cases like this. Never spotted that before, thanks.

In fact my target strings can also occur anywhere in a line. I'll remember to add that spec here in future.

Posted: Tue Nov 09, 2021 10:01 am
by ben_josephs
If the original comments can occur anywhere in a line, perhaps followed by further text on the same line, then the replacement will change

Code: Select all

/* Unhelpful comment */  doEssentialThing () ;
to

Code: Select all

//  Unhelpful comment   doEssentialThing () ;
which is plainly wrong.

What spec?

Posted: Tue Nov 09, 2021 12:22 pm
by AmigoJack
How about lines that have multiple comments? Such as:

Code: Select all

if( /*bOne and bTwo and*/ bThree /*and bFour*/ ) {
Also all regex patterns also match empty comments and I just cannot imagine any code that ever makes use of such. Let alone the void sense of turning that into another comment:

Code: Select all

/**/