views:

44

answers:

1

The problem: I'm trying to style certain keywords (e.g. "function") within the content of a code-tag, excluding those keywords from the C-style comments that appear in that content. Solution: I believe that a match of the innerHTML-string of the code-tag against a Regex-pattern, that would exclude the C-style comments could do the job...

Any suggestions?

+1  A: 

C-style comments can be nested and are therefore not suitable for a regular expression.

Matching an unnested C-style comment is simple:

/\*.*?\*/

Allowing one level of nesting results in:

/\*(?:(?!\*/|/\*).)*+(?:/\*(?:(?!\*/|/\*).)*+\*/(?:(?!\*/|/\*).)*+)*+.*?\*/

(taken from RegexBuddy's library). Try to imagine what happens if you allow more.

I understand your question as "Is it possible for a regular expression to match a block of text that is outside of C-style comments?" - this would be even more complex than this. Imagine a string like "This is used to start a C comment: /*". Furthermore, if you still wanted to try this, you'd need lookbehind which JavaScript doesn't support.

Tim Pietzcker