The regular expression matches only if the subpattern does not match

I am trying to combine C style comments with a file, but only if the comment does not start with specific tags entered by @

For example, from

 /* some comment to match */ /* another comment. this should match also */ /*@special shouldn't match*/ 

Is it possible to use only regular expressions?

I am trying to use javascript with regular expressions.

+4
source share
3 answers
 /\*\s*( ?!@ )(?:(?!\*/).)*\*/ 

Interrupted as:

  / \ * // "/ *"
 \ s * // optional space
 ( ?!@ ) // not followed by "@"
 (?: // don't capture ...
    (?! \ * /).  // ... anything that is not "* /"
 ) * // but match it as often as possible
 \ * / // "* /"

Use in global and dotall mode (for example, the dot should also match new lines)

A common warning word: like all parsing jobs that run with regular expressions, this will lead to a crash on nested patterns and broken input.

emk points out a good example of input (otherwise valid) that will cause this expression to break. This cannot help, regular expression is not for parsing. If you are sure that such things can never happen in your input, a regular expression may still work for you.

+4
source

You can start with something like this:

 /\*[^@] 

But overall you don’t look to combine C-style comments with regular expressions due to unpleasant corner cases. Consider:

 "foo\" /* " " */ " 

There are no comments in this code (this is a concatenation of two string compilation literals), but you cannot parse it without a real parser. (Technically, you can use regex because you only need a simple state machine, but it is a very disgusting regex.)

+1
source

use negative view

0
source

All Articles