Fix the mention extractor for chat messages

Review the AI's codeMedium15 min

Your task

Your chat app notifies users when someone @mentions them. An AI's first regex, @(\w+), fired on email addresses like a@gmail.com and on @property inside code blocks, and it missed @jean-luc. You wrote down the product's mention rules, and the new extractor follows them.

An assistant wrote extract_mentions(text). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • text: one chat message.
  • Return the mentioned handles, without the @, each once, in order of first appearance.

Rules the tests check:

  • Read the message left to right. Three backticks in a row open a code block, and the next three backticks close it. Nothing inside a code block is a mention. A block that is never closed runs to the end of the message.
  • Outside code, an @ starts a mention only when it is the first character of the message or the character before it is not an ASCII letter or digit. The character right after the @ must be an ASCII letter.
  • The handle is the longest run of ASCII letters, digits, _ and - that starts right after the @.
  • Keep a handle only if it is 2 to 30 characters long. A longer run is dropped, not cut short. Either way, keep reading after the run.
  • Handles compare exactly, case included.

Examples

extract_mentions(text: str) -> list[str]
Example 1
Inputextract_mentions("hey @alice and @bob_smith")
Output["alice", "bob_smith"]
Example 2
Inputextract_mentions("mail a@gmail.com now")
Output[]
Example 3
Inputextract_mentions("see ```@property``` but @data_team wins")
Output["data_team"]