代码之家  ›  专栏  ›  技术社区  ›  Hakan Ensari

正则表达式来匹配行首或空格字符后的模式

  •  1
  • Hakan Ensari  · 技术社区  · 16 年前

    /^#(\w+)|\s#(\w+)/i
    

    这行不通:

    /^|\s#(\w+)/i
    

    不,我不想在开始的时候用逗号隔开:

    /(^|\s)#(\w+)/i
    

    我正在用Ruby做这件事——尽管我认为这与此无关。

    要给出匹配字符串和非匹配字符串的一些示例,请执行以下操作:

    '#hashtag it is'        # should match => [["hashtag"]]
    'this is a #hashtag'    # should match => [["hashtag"]]
    'this is not a#hashtag' # should not match => []
    

    有什么建议吗?我在挑剔吗?

    3 回复  |  直到 16 年前
        1
  •  4
  •   Amber    16 年前
    /(?:^|\s)#(\w+)/i
    

    添加 ?: 第一个组的前缀将导致它不是匹配组,因此只有第二个组实际上是匹配组。因此,字符串的每个匹配项都将有一个捕获组,其内容将是hashtag。

        2
  •  5
  •   Simone Carletti    16 年前

    /\B#(\w+)/i
    
    "this is a #hash tag"      # matches
    "#hash tag"                # matches
    "this is not#hash tag"     # doesn't match
    
        3
  •  0
  •   Amarghosh    16 年前

    它使用lookbehind,我不知道Ruby是否支持lookbehind(我听说JavaScript不支持它们)

    /(^#(\w+))|((?<= )#(\w+))/