Regex match comments and quotes UPDATE

New regex - covers escaped slashes and uses lazy qualifiers:

/(?&gt;(')(?&gt;(?&gt;\\\\)|\\'|.)*')|(?&gt;(")(?&gt;(\\\\)|(?&gt;\\")|.)*")|(?&gt;((?&gt;\/\/|#)).*^)|(?&gt;(\/\*).*\*\/)/msU


Here are the different parts:

Single quotes: (?&gt;(')(?&gt;(?&gt;\\\\)|\\'|.)*')

Double quotes: (?&gt;(")(?&gt;(\\\\)|(?&gt;\\")|.)*")

Single line comments: (?&gt;((?&gt;\/\/|#)).*^)

Multiline comments: (?&gt;(\/\*).*\*\/)

I moved the html comments to a different regex because html will be handled differently.

Here's an example of what it does: (The matched parts are bold)



//single line comment

random text ... #another comment

Multiline comments:

/* this is a multiline comment

matches the whole thing
*/

Quotes:

"also matches strings with \" escaped quotes or 'the other kind of quotation marks in it' "

'matches the end quote because it it not escaped \\'



This is the original post:

I'm working on making syntax highlighting on my blog, and I created a regex to match strings and comments (I'm going to make a callback function to format each differently)

Here's my regex:

(?&gt;(")(?&gt;[^"]|(?&gt;(?&lt;=\\)"))*")|(?&gt;(')(?&gt;[^']|(?&lt;=\\)')*')|(?&gt;((?&gt;\/\/|#))[^\n\r]*)|(?&gt;(\/\*)(?&gt;.(?!\*\\))*\*\/)|(?&gt;(&lt;!--)(?&gt;.(?!--&gt;))*.--&gt;)


I tested it and it seemed to work, but is there anything I'm missing or an easier  way to do it? It currently matches strings ("...", '...') and takes into account escaped chars and strings within other strings. It also matches comments (//..., #..., /*...*/, &lt;!--...--&gt;).

Here's what I'm using each part of the regex for:

Part 1: (?&gt;(")(?&gt;[^"]|(?&gt;(?&lt;=\\)"))*"): Match strings quoted with "

Part 2: (?&gt;(')(?&gt;[^']|(?&lt;=\\)')*'): Match strings quoted with '

Part 3: (?&gt;((?&gt;\/\/|#))[^\n\r]*): Match single line comments # or //

Part 4: (?&gt;(\/\*)(?&gt;.(?!\*\\))*\*\/): Match multiline comments /*...*/

Part 5: (?&gt;(&lt;!--)(?&gt;.(?!--&gt;))*.--&gt;): Match html comments &lt;!--...--&gt;
If it is PHP source code you want to highlight, why not use the tokenizer that's build into PHP itself? I use that and it seems to work fine:

$tokens = token_get_all($sourceCode);


Then all you have to do is walk through all the tokens and give them a color.

See: https://www.php.net/manual/en/function.token-get-all.php

No extra library, no faffing around with endless regular expressions.