代码之家  ›  专栏  ›  技术社区  ›  brian d foy

你能挽救我的否定回溯示例来证明数字吗?

  •  17
  • brian d foy  · 技术社区  · 16 年前

    Mastering Perl

    在讨论lookarounds一节中,我想使用一个负lookback来实现带有小数部分的数字的具体化例程。关键是要使用负面回顾,因为这就是主题。

    $_ = '$1234.5678';
    s/(?<!\.\d)(?<=\d)(?=(?:\d\d\d)+\b)/,/g;  # $1,234.5678
    

    这个 (?<!\.\d) 断言 (?=(?:\d\d\d)+\b) 不是小数点和数字。

    $_ = '$1234.56789';
    s/(?<!\.\d)(?<=\d)(?=(?:\d\d\d)+\b)/,/g;  # $1,234.56,789
    

    如果lookbehinds在Perl中可以是可变宽度的,那么这将非常容易。但他们不能。

    请注意,在没有负面回顾的情况下很容易做到这一点,但这不是示例的重点。有没有办法挽救这个例子?

    3 回复  |  直到 16 年前
        1
  •  14
  •   Michael Carman    16 年前

    我不认为没有某种形式的可变宽度后视是可能的。增加 \K 消极的 回头看看,但只要有一点创造力和许多丑陋,我们就能让它发挥作用:

    use 5.010;
    $_ = '$1234567890.123456789';
    s/(?<!\.)(?:\b|\G)\d+?\K(?=(?:\d\d\d)+\b)/,/g;
    say;  # $1,234,567,890.123456789
    

    /x

    s/
      (?<!\.)        # Negative look-behind assertion; we don't want to match
                     # digits that come after the decimal point.
    
      (?:            # Begin a non-capturing group; the contents anchor the \d
                     # which follows so that the assertion above is applied at
                     # the correct position.
    
        \b           # Either a word boundary (the beginning of the number)...
    
        |            # or (because \b won't match at subsequent positions where
                     # a comma should go)...
    
        \G           # the position where the previous match left off.
    
      )              # End anchor grouping
    
      \d+?           # One or more digits, non-greedily so the match proceeds
                     # from left to right. A greedy match would proceed from
                     # right to left, the \G above wouldn't work, and only the
                     # rightmost comma would get placed.
    
      \K             # Keep the preceding stuff; used to fake variable-width
                     # look-behind
    
                     # <- This is what we match! (i.e. a position, no text)
    
      (?=            # Begin a positive look-ahead assertion
    
        (?:\d\d\d)+  # A multiple of three digits (3, 6, 9, etc.)
    
        \b           # A word (digit) boundary to anchor the triples at the
                     # end of the number.
    
      )              # End positive look-ahead assertion.
    /,/xg;
    
        2
  •  4
  •   cjm    16 年前

    本着这种精神,自动拼写更正器怎么样?

    s/(?<![Cc])ei/ie/g; # Put I before E except after C
    

        3
  •  0
  •   willert    16 年前

    我不认为这是您想要的(特别是因为否定的look-behind断言已经被删除),但我想,您唯一的选择是像本例中那样将小数点后的位置模糊起来:

    s/
      (?:
        (?<=\d)
        (?=(?:\d\d\d)+\b)
       |
        ( \d{0,3} \. \d+ )
      )
     / $1 ? $1 : ',' /exg;
    

    另外,我认为这是一个很好的例子,当它没有作为书中的第一个例子使用时,因为它展示了环视断言的一些陷阱和局限性。