Fix caption mentions being missed after a newline

_mention_regex required the character before '@' to be a non-word
character other than '\n', so a mention at the start of a new line was
never matched. The '\n' exclusion was introduced in 8784ac7 when the
prefix went from '\W' to '[^\w\n]'; restoring '\W' matches mentions
after a newline while still keeping email addresses out of the results,
since the character before '@' in an address is a word character.

Also affects Profile.biography_mentions and StoryItem.caption_mentions,
which share the same regex.

Fixes #2709
This commit is contained in:
Joseph May
2026-07-13 20:48:06 +02:00
committed by Alexander Graf
parent 297a88f252
commit ad03b392db
2 changed files with 24 additions and 1 deletions
+1 -1
View File
@@ -152,7 +152,7 @@ _hashtag_regex = re.compile(r"(?:#)((?:\w){1,150})")
# support Unicode and a word/beginning of string delimiter at the beginning to ensure # support Unicode and a word/beginning of string delimiter at the beginning to ensure
# that no email addresses join the list of mentions. # that no email addresses join the list of mentions.
# http://blog.jstassen.com/2016/03/code-regex-for-instagram-username-and-hashtags/ # http://blog.jstassen.com/2016/03/code-regex-for-instagram-username-and-hashtags/
_mention_regex = re.compile(r"(?:^|[^\w\n]|_)(?:@)(\w(?:(?:\w|(?:\.(?!\.))){0,28}(?:\w))?)", re.ASCII) _mention_regex = re.compile(r"(?:^|\W|_)(?:@)(\w(?:(?:\w|(?:\.(?!\.))){0,28}(?:\w))?)", re.ASCII)
def _optional_normalize(string: Optional[str]) -> Optional[str]: def _optional_normalize(string: Optional[str]) -> Optional[str]:
+23
View File
@@ -210,5 +210,28 @@ class TestInstaloaderLoggedIn(TestInstaloaderAnonymously):
break break
class TestCaptionMentions(unittest.TestCase):
"""Caption parsing, which requires no network access."""
@staticmethod
def _post_with_caption(caption: str) -> instaloader.Post:
return instaloader.Post(None, {"shortcode": "BhrEy4nBFVU", "caption": caption})
def test_caption_mentions(self):
for caption, expected in [
("@alice at the beginning", ["alice"]),
("preceded by a space @bob", ["bob"]),
("preceded by a newline\n@carol", ["carol"]),
("multiple lines\n@dave\n@erin", ["dave", "erin"]),
("no mentions here", []),
]:
with self.subTest(caption=caption):
self.assertEqual(self._post_with_caption(caption).caption_mentions, expected)
def test_caption_mentions_ignores_email_addresses(self):
post = self._post_with_caption("write to alice@example.com\ncontact @bob instead")
self.assertEqual(post.caption_mentions, ["bob"])
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()