正则表达式保留/匹配任何以特定字符开头的单词

regexp keep/match any word that starts with a certain character

本文关键字:字符 开头 单词 保留 任何 正则表达式      更新时间:2023-09-26

我只想保留以 # 或 @ 开头的字符串

  1. 福巴@sushi - 芥末
  2. 福巴 #sushi - 辣根

因此,仅匹配@susui或删除其周围的文本。PHP 或 JavaScript。

根据你如何定义"单词",你可能想要

(?<='s|^)[@#]'S+

(?<='s|^)[@#]'w+

解释:

(?<='s|^)  # Assert that the previous character is a space (or start of string)
[@#]       # Match @ or #
'S+        # Match one or more non-space characters
(or 'w+)   # Match one or more alphanumeric characters.

所以,在 PHP 中:

preg_match_all('/(?<='s|^)[@#]'S+/', $subject, $result, PREG_PATTERN_ORDER);

为您提供一个数组$result字符串$subject中的所有匹配项。在 JavaScript 中,这是行不通的,因为 lookbehinds("Assert..."部分从正则表达式的开头)不受支持。