Search code examples
regexnumberssymbolswords

Simple regex - finding words including numbers but only on occasion


I'm really bad at regex, I have:

    /(@[A-Za-z-]+)/

which finds words after the @ symbol in a textbox, however I need it to ignore email addresses, like:

    foo@things.com

however it finds @things

I also need it to include numbers, like:

    @He2foo

however it only finds the @He part.

Help is appreciated, and if you feel like explaining regex in simple terms, that'd be great :D


Solution

  • /(?:^|(?<=\s))@([A-Za-z0-9]+)(?=[.?]?\s)/
    

    @This (matched) regex ignores@this but matches on @separate tokens as well as tokens at the end of a sentence like @this. or @this? (without picking the . or the ?) And yes email@addresses.com are ignored too.

    The regex while matching on @ also lets you quickly access what's after it (like userid in @userid) by picking up the regex group(1). Check PHP documentation on how to work with regex groups.