Regex for parsing mentioned usernames from Instagram captions

Viewed 378

I've been trying to create a Regex to parse mentioned usernames from Instagram captions.

@men.tion._, @men.tion._, @men.tion._., (@men.tion._), and (@men.tion._.) should all return men.tion._. Feel free to correct me if this is incorrect — I haven't been able to find any information on how Instagram parses the usernames itself.

So far, I've come up with (?<=(^|\W)@)(?<username>[\w\._]+)(?=(\.|\W)), but it doesn't quite work.

1 Answers

You may use

\B@(?<username>\w+(?:\.\w+)*)

Details

  • \B@ - a @ that is either at the start of string or a non-word char
  • (?<username>\w+(?:\.\w+)*) - Group "username":
    • \w+ - 1+ word chars
    • (?:\.\w+)* - 0 or more repetitions of . and 1+ word chars.

See regex demo.

Related