1

I have tried a lot doing this using RegExp.

Pattern: \*.*\*!

Test text:

/**!
 * Plugin Name 1.0.0
 * @author  Name
 */

/*! Test */

/* Test */

/************************************************************************/
/******/ /* Test */
/******/
/*!*********************!*\
  !*** ./index.ts ***!
  \*********************/

Link for test: https://regexr.com/6eoa0

It works great and matches the first comment and that's what I need, but for some reason, it matches the other two comments.

How can make it detect comments that start with **! (in one line).

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
John
  • 161
  • 1
  • 13
  • Use a javascript parser - regex is not powerful enough to cover every scenario here. – ASDFGerte Feb 04 '22 at 17:56
  • This part `\*.*` matches _zero_ or more asterisks, then followed by `\*!` — so `/*!` is zero-asterisks then '*!' which matches. You want _at least two_ asterisks which would be `\*\*+!` -- plus matches _one or more_ instead of _zero or more_. (I'm assuming you also want `/*****!` — if you want _exactly_ two it's just `\*\*!` no need for `+` or `*`) – Stephen P Feb 04 '22 at 19:58
  • @ASDFGerte — the pon̷y he comes... https://stackoverflow.com/a/1732454/238884 – Michael Lorton Feb 04 '22 at 20:06

1 Answers1

2

You can use

/\/\*\*![^*]*\*+(?:[^\/*][^*]*\*+)*\//g

See the regex demo. Details:

  • \/\*\*! - a /**! string
  • [^*]* - zero or more chars other than asterisks
  • \*+ - one or more asterisks
  • (?:[^\/*][^*]*\*+)* - zero or more sequences of
    • [^\/*] - any char other than a / and *
    • [^*]* - zero or more chars other than asterisk
    • \*+ - one or more asterisks
  • \/ - a / char.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • The question isn't fully clear about where these comments reside, but i am assuming javascript syntax. There are a lot of small issues, e.g. fake comments in string literals: `'/**!'/* */`. While those maybe can be dealt with in an extremely complex regex (what about `'\'/**!*/'`?), a real brick wall are nested template literals, as you can embed more template literals inside one, and each embed can include real comments (`\`${\`/**!\`/**/)}\``). It's hardly ever done, but valid javascript. – ASDFGerte Feb 04 '22 at 20:18