【问题标题】:regexp keep/match any word that starts with a certain character正则表达式保留/匹配以某个字符开头的任何单词
【发布时间】:2012-06-25 15:27:43
【问题描述】:

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

  1. foobar @sushi - 芥末
  2. foobar #sushi - 辣根

因此只匹配 @susui 或删除它周围的文字。 PHP 或 JavaScript。

【问题讨论】:

    标签: php javascript regex


    【解决方案1】:

    根据你如何定义一个“词”,你可能想要

    (?<=\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);
    

    为您提供字符串$subject 中所有匹配项的数组$result。在 JavaScript 中,这不起作用,因为不支持后视(正则表达式开头的“断言...”部分)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-17
      • 2013-11-23
      相关资源
      最近更新 更多