Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to remove comments endings

I am trying to create a regex that I can use to remove any closing comment syntax out of string.

For instance if I had:

/* help::this is my comment */ should return this is my comment or <!-- help:: this is my other comment --> should return this is my other comment. Ideally I would like to target all major programming languages that require ending comment tags.

Here is what I have so far:

function RemoveEndingTags(comment){
    return comment.split('help::')[1].replace("*/", "").replace("-->", ""); //my ugly solution
}

An HTML markup example would be:

<!-- help:: This is a comment -->
<div>Hello World</div>

so the string would be help:: This is a comment -->

like image 264
Luca Avatar asked May 30 '15 04:05

Luca


1 Answers

This should support many languages including bash which doesn't support \s:

help::[\r\n\t\f ]*(.*?)[\r\n\t\f ]*?(?:\*\/|-->)

You can also use Which prevents any un-necassary selection making this easier to use also:

help::[\r\n\t\f ]*(.*?)(?=[\r\n\t\f ]*?\*\/|[\r\n\t\f ]*?-->)

You could use this as a funky .replace but it might result in quirky behavior:

/\/\*[\r\n\t\f ]*help::|<!--[\r\n\t\f ]*help::|[\r\n\t\f ]\*\/|[\r\n\t\f ]*-->/g

Explanation

Solution 1:

help::            Matches the text "help::"
[\r\n\t\f ]*      Matches any whitespace character 0-unlimited times
(.*?)             Captures the text
[\r\n\t\f ]*?     Matches all whitespace
(?:               Start of non-capture group
   \*\/           Matches "*/"
|                 OR
   -->            Matches "-->"
)                 End non capture group

[\r\n\t\f ]

\r Carriage return
\n Newline
\t Tab
\f Formfeed
   Space

Solution 2 (supports almost everything)

help::             Matches "help::"
[\r\n\t\f ]*       Matches all whitespace 0-unlimited
(.*?)              Captures all text until...
(?=                Start positive lookahead
    [\r\n\t\f ]*?  Match whitespace 0-unlimited
    \*\/           Matches "*/"
|                  OR
    [\r\n\t\f ]*?  Match whitespace 0-unlimited
    -->            Matches "-->"
)

Demo 1

Demo 2

like image 106
Downgoat Avatar answered Sep 29 '22 23:09

Downgoat