English 中文(简体)
变数清单中的变数模式
原标题:Metaquoting patterns in a variable list

我有一份清单,列出我想在座的格局。 这些模式是多种多样的,包含着无数的果园,我想说的是,这些果园是真的。 因此,这完全适用于引用<代码>的计量。 Q.E。 复杂性在于,我需要加入各种模式清单,定期表达。

use strict;
use warnings;
# sample string to represent my problem
    my $string = "{{a|!}} Abra
{{b|!!}} {{b}} Hocus {{s|?}} Kedabra
{{b|+?}} {{b|??}} Pocus
 {{s|?}}Alakazam
";

# sample patterns to look for    
my @patterns = qw({{a|!}} {{s|?}} {{s|+?}} {{b|?}});
# since these patterns can be anything, I join the resulting array into a variable-length regex
my $regex = join("|",@patterns);

my @matched = $string =~ /$regex(sw+s)/; # Error in matching regex due to unquoted metacharacters
print join("", @matched); # intended result: Hocus
 Pocus

当我试图在加入行动中引入美文时,似乎没有任何效果。

# quote all patterns so that they match literally, but make sure the alternating metacharacter works as intended
my $qmregex = "Q".join("E|Q", @patterns)."E";

my @matched = $string =~ /$qmregex(sw+s)/; # The same error

出于某种原因,在插图一中,该缩略语作为常规表达方式时,不会产生影响。 对我来说,他们只是在直接添加到<条码>/Q$anexpressionE/的栏目中时,才工作,但就我而言,我可以说,这并不是一种选择。 我如何处理这个问题?

问题回答

我不理解你的预期结果,因为<条码>Abra和<条码>Kedabra是任何一种模式之前的唯一指示。

为了解决你的问题,你必须单独填写<代码>Q和 E。 只影响显示的体值,即<代码>Q>和>E。 页: 1

my $qmregex = join  | , map "Q$_E", @patterns;

但是,使用<代码>代号的功能更为简单。

您还必须附上括号中的名单(......),以孤立更改,并适用/g / modifier to the regex对座标,以在座标内发现所有 o。

Try

use strict;
use warnings;

my $string = "{{a|!}} Abra
{{b|!!}} {{b}} Hocus {{s|?}} Kedabra
{{b|+?}} {{b|??}} Pocus
 {{s|?}}Alakazam
";

my @patterns = qw(  {{a|!}} {{s|?}} {{s|+?}} {{b|?}}  );

my $regex = join  | , map quotemeta, @patterns;
my @matched = $string =~ /(?:$regex)(sw+s)/g;
print @matched;

 Abra
 Kedabra




相关问题
Why does my chdir to a filehandle not work in Perl?

When I try a "chdir" with a filehandle as argument, "chdir" returns 0 and a pwd returns still the same directory. Should that be so? I tried this, because in the documentation to chdir I found: "...

How do I use GetOptions to get the default argument?

I ve read the doc for GetOptions but I can t seem to find what I need... (maybe I am blind) What I want to do is to parse command line like this myperlscript.pl -mode [sth] [inputfile] I can use ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...

热门标签