bri*_*foy 17 regex perl lookbehind
在Mastering Perl的"高级正则表达式"一章中,我有一个简单的例子,我无法找到一个很好的解决方案.这个例子可能是为了自己的利益而过于聪明,但也许有人可以为我解决它.可能有一本书的免费副本用于工作修复.:)
在讨论lookarounds的部分中,我想使用负向lookbehind来实现具有小数部分的数字的通用例程.关键是要使用负面的后视,因为那是主题.
我愚蠢地这样做了:
$_ = '$1234.5678';
s/(?<!\.\d)(?<=\d)(?=(?:\d\d\d)+\b)/,/g; # $1,234.5678
Run Code Online (Sandbox Code Playgroud)
该(?<!\.\d)断言之前,该位(?=(?:\d\d\d)+\b)是不是小数点和一个数字.
愚蠢的事情并不是在努力打破它.通过在末尾添加另一个数字,现在有一组三个数字,前面没有小数点和数字:
$_ = '$1234.56789';
s/(?<!\.\d)(?<=\d)(?=(?:\d\d\d)+\b)/,/g; # $1,234.56,789
Run Code Online (Sandbox Code Playgroud)
如果在Perl中lookbehinds可以是可变宽度,那么这将非常简单.但他们不能.
请注意,这样做很容易,没有负面的后观,但这不是示例的重点.有没有办法挽救这个例子?
Mic*_*man 14
如果没有某种形式的可变宽度后视镜,我认为这是不可能的.\K在5.10中添加断言提供了一种伪装可变宽度正向后视的方法.我们真正需要的是可变宽度的负面观察,但是有一点创造力和很多丑陋我们可以使它工作:
use 5.010;
$_ = '$1234567890.123456789';
s/(?<!\.)(?:\b|\G)\d+?\K(?=(?:\d\d\d)+\b)/,/g;
say; # $1,234,567,890.123456789
Run Code Online (Sandbox Code Playgroud)
如果有一种模式要求/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;
Run Code Online (Sandbox Code Playgroud)