Search code examples
phpregexpreg-matchpreg-replace-callback

I'm trying to preg_match a word, beginning with an @, not contained in sqaure brackets


That is to say, alice should be matched, but bob shouldn't in the following

Hello @alice and [@bob](...)

I can match the names themselves with the following simple regex: /\@([\w]+)/.

Does anyone know how to make the regex not match bob?


Solution

  • Group index 1 contains the characters you want.

    Use a negative looahead.

    @(?![^\[\]]*])(\w+)
    

    DEMO

    OR

    Through alteration,

    \[.*?\]|@(\w+)
    

    DEMO

    OR

    Through PCRE verb (*SKIP)(*F)

    \[.*?\](*SKIP)(*F)|@(\w+)
    

    DEMO