2

This would greatly improve the readability of many regular expressions I write, and when I write a single literal space in my regexes I almost always mean \s* anyway. So, is there a "mode" in Perl regular expressions that enables this, like /s to make . match newlines, etc.? A cursory read through perlre didn't give anything, but maybe I missed something or maybe there's a different way to achieve this?

Edit: What I mean is, currently I write qr/^\s*var\s+items\s*=\s*[\s*$/, and I'd instead like to write qr/^ var\s+items = [ $/ and have it mean the same thing using some means- and my question is whether such a means exists.

4

2 回答 2

6

这是使用重载 ( http://perldoc.perl.org/perlre.html#Creating-Custom-RE-Engines ) 进行特定替换的示例。

我的.pm

package myre;
use overload;

sub import {
    overload::constant 'qr' => \&spacer;
}

sub spacer {
     my $re = shift;
     $re =~ s/ /qr{\s*}/ge;
     return $re;
}
1;

例子.pl

use myre;
print "ok" if "this is\n\n a   test" =~ /this is a test/;
于 2013-10-02T02:43:13.150 回答
6

不,没有这样的功能可用。但是有一种/x模式可以防止文字空间完全匹配任何内容,以便您可以直观地构建您的正则表达式。

qr/\A\s* var \s* items \s*=\s* \[ \s*\z/x

(字符类除外——[ ]再次匹配空格)。

于 2013-10-01T20:50:07.147 回答