【问题标题】:Problem with quantifiers and look-behind量词和后视问题
【发布时间】:2010-08-13 17:04:29
【问题描述】:
### Ruby 1.8.7 ###

require 'rubygems'
require 'oniguruma' # for look-behind

Oniguruma::ORegexp.new('h(?=\w*)')
# => /h(?=\w*)/

Oniguruma::ORegexp.new('(?<=\w*)o')
# => ArgumentError: Oniguruma Error: invalid pattern in look-behind

Oniguruma::ORegexp.new('(?<=\w)o')
# => /(?<=\w)o/


### Ruby 1.9.2 rc-2 ###

"hello".match(/h(?=\w*)/)
# => #<MatchData "h">

"hello".match(/(?<=\w*)o/)
# => SyntaxError: (irb):3: invalid pattern in look-behind: /(?<=\w*)o/

"hello".match(/(?<=\w)o/)
# => #<MatchData "o"> 

我不能使用带有后视功能的量词?

【问题讨论】:

    标签: ruby regex


    【解决方案1】:

    问题在于 Ruby 不支持可变长度的lookbehinds。量词本身并没有出现,但它们不会导致后视的长度是不确定的。

    Perl 具有相同的限制,几乎所有具有正则表达式的主要语言也是如此。

    尝试使用直接匹配 (\w*)\W*?o 而不是后向匹配。

    【讨论】:

      【解决方案2】:

      我正在努力解决同样的问题,Borealid 的回答很好地解释了这个问题。

      然而,这让我开始思考。也许量词不需要在lookbehind inside,但可以应用于lookbehind 本身?

      "hello".match(/(?<=\w*)o/)
      # => SyntaxError: (irb):3: invalid pattern in look-behind: /(?<=\w*)o/
      
      "hello".match(/(?<=\w)*o/)
      # => #<MatchData "o">
      

      所以现在我们有可变数量的恒定长度的lookbehinds。似乎绕过了我的问题。 :)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-13
        • 1970-01-01
        • 2019-10-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 2011-06-24
        • 1970-01-01
        相关资源
        最近更新 更多