正则表达式仅匹配首个项问题:为何无法匹配所有@提及与#话题?
Let’s break down why you’re only getting the first match, even though the + quantifier is greedy:
The greedy
+doesn’t control global matching: The+just tells the regex engine to grab as many characters as possible within a single match—it doesn’t make the engine scan the entire string for all possible matches. That behavior is controlled by the global matching flag (usually thegflag in regex flavors like JavaScript, or using functions likere.findall()in Python instead ofre.search()). If you haven’t enabled this, your regex will stop after finding the first valid match.Your current regex consumes whitespace, but that’s not the main issue: The
(^|\s)part matches either the start of the string or a whitespace character, and it uses up that whitespace. For example, if your string is@alice #bob, the first match will use the^anchor to grab@alice, then the next match will start at the space after@alice—it will match that space and then#bob, so this should work if global matching is enabled. The only time this fails is if your matches lack whitespace separators (like@alice@bob), where the second@isn’t preceded by whitespace or the start of the string.
Fixes & Optimizations
Turn on global matching: Make sure you’re using a tool or function that looks for all matches (check the "Global" box in regex101, add the
gflag in JavaScript, usere.findall()in Python, etc.).Avoid consuming whitespace with a zero-width assertion: If you don’t want leading whitespace in your match results, use a negative lookbehind instead of matching whitespace directly. This checks the position without using up any characters:
(?<!\S)([#@][a-z\d-]+)The
(?<!\S)ensures the character before the@/#is either the start of the string or a whitespace character. Now your captured group will only contain the mention/hashtag itself, no extra spaces to strip later.
内容的提问来源于stack exchange,提问作者joao-m-santos

