繁体   English   中英

为什么这种消极面目背后错了?

[英]Why is this negative look behind wrong?

def get_hashtags(post)
    tags = []
    post.scan(/(?<![0-9a-zA-Z])(#+)([a-zA-Z]+)/){|x,y| tags << y}
    tags
end

Test.assert_equals(get_hashtags("two hashs##in middle of word#"), [])
#Expected: [], instead got: ["in"]

它不应该回头看看比赛是否不是以单词或数字开头吗? 为什么仍然接受“中”作为有效匹配?

您应使用\\K而不要使用负数。 这使您可以大大简化正则表达式:无需预定义的数组,捕获组或块。

\\K表示“丢弃到目前为止所有匹配的内容”。 这里的关键是可变长度匹配可以在\\K之前,而(在Ruby和大多数其他语言中)在(负或正)lookbehind中不允许可变长度匹配。

r = /
    [^0-9a-zA-Z#] # do not match any character in the character class
    \#+           # match one or more pound signs
    \K            # discard everything matched so far
    [a-zA-Z]+     # match one or more letters
    /x            # extended mode

#\\#+我如果不写在扩展模式正则表达式不需要进行转义。

"two hashs##in middle of word#".scan r
  #=> []

"two hashs&#in middle of word#".scan r
  #=> ["in"]

"two hashs#in middle of word&#abc of another word.###def ".scan r
   #=> ["abc", "def"] 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM