Home > Enterprise >  RegEx for twitter usernames
RegEx for twitter usernames

Time:05-23

I need some help with regex for usernames which start with "@" and following rules:

  1. Username includes only \w symbols.

  2. Match if string has any non word character except "@", e.g.

    • Match @username in @username!&?()*^
    • But don't match in @username@username, @username!@username or @username!%^@ (if string has at least one more "@").
  3. Don't match if string has any symbols before "@", e.g.

    • Don't match @username in not@username or !@username.

For now i have:

(?<!\w)@(\w{4,15})\b(?!@)

Which excludes only \w symbols before and "@" if it stands only after username.

CodePudding user response:

You can assert a whitespace boundary to the left, and assert not @ in the line to the right.

(?<!\S)@(\w{4,15})\b(?![^@\n]*@)

Explanation

  • (?<!\S) Assert a whitespace boundary to the left
  • @ Match literally
  • (\w{4,15})\b Capture 4-15 word chars followed by a word boundary
  • (?![^@\n]*@) Assert not optional repetitions of any char except @ or a newline to the right followed by @

Regex demo

  • Related