Regex between tags unless escaped

前端 未结 1 1938
伪装坚强ぢ
伪装坚强ぢ 2021-01-25 00:12

I made a PHP wrapper around Pygments library that highlights code blocks. Regex used for codeblocks detection can be configured in configuration file. (json for

相关标签:
1条回答
  • 2021-01-25 00:27

    What you need is a rather tricky regex feature called a "zero-width negative look-behind assertion". "Zero-width" meaning it matches zero characters of the input, "negative" meaning it succeeds only if it is not found, and "look-behind" meaning it looks backwards.

    The syntax for this is (?<!test) where test is the thing you want to not be there.

    In your case, you want to match a [ but ignore it if preceded by a \, both of which need escaping, so you need (?<!\\)\[

    So your regex ends up as (in PHP) $re = '/(?<!\\\\)\[pygments=(.*?)\](.*?)\[\/pygments\]/';

    According to json_encode, that then ends up as "\/(?<!\\\\)\\[pygments=(.*?)\\](.*?)\\[\\\/pygments\\]\/" in JSON. I think my eyes are beginning to go funny with all the backslashes... ;)

    0 讨论(0)
提交回复
热议问题