0

I have a PHP file open in editor like Geany/Notepad++ which has both type of comments single-line and block-comments.

Now as block-comments are useful for documentation, I only want to remove single-line comments starting with //~ or #. Other comments starting with // should remain if they are not starting line from //.

How can I do that with a regular expression? I tried this one below, but I get stuck up in escaping slash and also including #.

^[#][\/]{2}[~].*

1 Answer 1

3

The problem with the regex ^[#][\/]{2}[~].* is that it matches a line starting with #//~.

The regex is the same as

^#\/\/~.*

Use the regex

^\s*(\/\/|#).*

Demo

Description:

The single-line comments can start at the beginning of the line or after a few spaces (indentation).

  1. ^: Start of the line
  2. \s*: Any number of spaces
  3. (\/\/|#): Match // or # characters. | is OR in regex.
  4. .*: Match any characters(except newline) any number of times

Note that PHP comments does not contain tilde ~ after //. Even if ~ is present after //, as the above regex checks for // and doesn't care for the characters after it, the comment with //~ will also be matched.

Sign up to request clarification or add additional context in comments.

10 Comments

What makes you think that comments don't contain ~?
@u_mulder I see it in official doc and didn't found that syntax.
In Geany when comment short-cut(Ctrl + E) is applied the comments applied contain //~
Comments should start with //. But after that I can write any symbols.
@u_mulder Right. But ~ is not mandatory, I've updated the answer. Also, previous regex ^\s*(\/\/|#).* will match that type of comments too since it starts with //.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.