我需要一个常规的EXP,该EXP在
[]
.之间找到所有文本。 我写了这篇文章:
my @matched = grep {$_ ne ""} map { m/\[(.*?)\]/; $1; } @Array;
a
,
$Array[0]
,
e
。
我想让所有这些像$Array[2]
a,b,c
。
$Array[0]
主要技巧是使用
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
my @Array;
$Array[0]= "[a][b][c] good bad";
$Array[1]= "[d] apple";
$Array[2]= "[e][f] mango ";
$Array[3]= "[g] capgemini";
my @matched = map { m/\[(.*?)\]/g } @Array;
print Dumper \@matched;
ahoy!这种情况对于正则表达方式是一个非常大的陷阱。 进行
/g
全局匹配时,
m//g
直到字符串本身结束之前才会进行。 这是预期的行为。 first
的发生,返回true,并且直到字符串结束之前才继续搜索。如果您希望全局匹配继续到字符串的末尾,则必须在一段时间内将其放置在此过程中。
m//g
该作品的方式是
m//g
匹配将返回true,直到不再匹配为止。 在不再匹配之后,它将返回false,并且循环将断开。 在场景的后面,Perl为每个字符串保持一个值。 比赛结束后,
while( m/\[(.*?)\]/g ){ print "$1\n"; }
值将在比赛后直接更新到该位置。 While循环的下一个迭代将开始从该位置搜索。 匹配失败后,m//g
值将重置为0。
在这里是说明此过程的代码,并显示了
pos
值如何在幕后工作...
pos
输出看起来像这样...
pos
这是一个令人沮丧的错误,因为大多数人都不知道pos
及其作用。 此工作的方式意味着每个搜索都有副作用。 基本上,#!/usr/bin/perl -w
my @strings = ("[a][b][c] good bad","[d] apple","[e][f] mango ","[g] capgemini",
"[h] then text [i]", "text first [j][k][l]",
"[more][than][one][letter]","[more than one word]");
for(@strings){
my $i = 1;
my $p = 0;
print "$_:\n";
while( /\[(.*?)\]/g ){
print "\titer: $i\tpos: $p\ttext: \"$1\"\n";
$p = pos; #pos value changes after each m//g global match
#the next m//g match on this string will always start from this position
$i++;
}
print "\n";
}
值在幕后发生变化,如果您不知道它的工作原理,将会产生意外的行为。 如果$ perl global.match.pl
[a][b][c] good bad:
iter: 1 pos: 0 text: "a"
iter: 2 pos: 3 text: "b"
iter: 3 pos: 6 text: "c"
[d] apple:
iter: 1 pos: 0 text: "d"
[e][f] mango :
iter: 1 pos: 0 text: "e"
iter: 2 pos: 3 text: "f"
[g] capgemini:
iter: 1 pos: 0 text: "g"
[h] then text [i]:
iter: 1 pos: 0 text: "h"
iter: 2 pos: 3 text: "i"
text first [j][k][l]:
iter: 1 pos: 0 text: "j"
iter: 2 pos: 14 text: "k"
iter: 3 pos: 17 text: "l"
[more][than][one][letter]:
iter: 1 pos: 0 text: "more"
iter: 2 pos: 6 text: "than"
iter: 3 pos: 12 text: "one"
iter: 4 pos: 17 text: "letter"
[more than one word]:
iter: 1 pos: 0 text: "more than one word"
值已更改,并且您想将值重置为字符串的开头,则必须使用相当奇怪的语法...
pos
这种情况并非完全直观,但是使用上述情况,而循环语法可能会得到您打算的结果。 请注意,
m//g
全局匹配将自动进入字符串的末尾。 因此,表现略有不同,这增加了混乱。
这里是关于pos
变量的一些文档。
pos
运气好!