18

Mastering Perl的“高级正则表达式”一章中,我有一个损坏的示例,我无法找到一个很好的修复方法。这个例子可能是为了自己的利益而试图过于聪明,但也许有人可以为我解决它。里面可能有这本书的免费副本,用于修复工作。:)

在讨论环视的部分中,我想使用否定的环视来实现带有小数部分的数字的 commifying 例程。关键是要使用负面的回顾,因为那是主题。

我愚蠢地这样做了:

$_ = '$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

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

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

4

3 回答 3

14

我认为没有某种形式的可变宽度后视是不可能的。5.10中添加的\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;
于 2010-02-25T21:03:45.893 回答
4

如果必须在 Stack Overflow 上发帖询问是否有人可以通过消极的后视来弄清楚如何做到这一点,那么这显然不是消极后视的一个很好的例子。你最好想出一个新的例子,而不是试图挽救这个例子。

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

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

(显然,这不是英语中的硬性规定,但我认为它是消极后视的更现实的应用。)

于 2010-02-25T00:10:10.020 回答
0

我不认为这就是你所追求的(特别是因为负面的后视断言已被删除),但我想,你唯一的选择是像这个例子中那样吞下小数位:

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

PS 我认为这是一个很好的例子,当它不被用作书中的第一个时,因为它展示了环视断言的一些陷阱和限制。

于 2010-02-25T08:42:19.300 回答