【发布时间】:2021-02-11 21:37:30
【问题描述】:
如何在 perl 中仅打印所有匹配项的捕获组? /g 似乎不起作用。
我认为我没有正确地使用if 语句,这就是我问的原因。正确的方法是怎样做的?(我在互联网上找不到任何有用的东西,我努力了好几个小时才让它最终起作用。)
$LONG_REGEX_WITH_TWO_CAPTURING_GROUPS="";
$file1="file1.html";
/* This part is complicated, this is why I said nothing
* about the two, but here is the result:
*
* Basically $2 (a letter) + whitespace + $1 (a filename)
* a file.txt
* b anotherfile.txt
* c 3rdfile.txt
* d 4thfile.txt
*
* I want it to become>
* a - (A specific part of the text in file.txt)
* b - (A specific part of the text in anotherfile.txt)
* etc.
*/
my $content1 = do { open my $fh, '<', $file1 or die $!; local $/; <$fh>; };
if ( $content1 =~ /$LONG_REGEX_WITH_TWO_CAPTURING_GROUPS/g ) {
# Print the letter first ($2).
print "$2 - ";
# Open the corresponding file (it's name is $1).
my $content2 = do { open my $fh, '<', $1 or die $!; local $/; <$fh>; };
# Try to complete the task.
if ( $content2 =~ /$SECOND_REGEX/g ) {
print "$1\n"; # There is just one capturing group.
}
}
但是,这只会打印第一个匹配项,即使它有一个全局标志。
如:
a - The desired text.
别管代码,问题很简单:如何只打印捕获组中的内容,但从所有匹配项中打印(或使其匹配文件中的所有内容)?
谢谢!
我正在编辑,所以我可以把代码放在这里:
#!/usr/bin/perl
$file1="file1.html";
my $content1 = do { open my $fh, '<', $file1 or die $!; local $/; <$fh>; };
foreach ( $content1 =~ m/LONG_REGEX_WITH_TWO_CAPTURING_GROUPS/g ) {
# If I were to put a print "$content1"; here, the program would have
# no output. Here is the problem, the question still remains.
print "$2 - ";
my $content2 = do { open my $fh, '<', $1 or die $!; local $/; <$fh>; };
foreach ( $content2 =~ m/SECOND_REGEX>/g ) {
print "$1\n"; # There is just one capturing group.
}
}
这对我有用:
#!/usr/bin/perl
$file1="file1.html";
my $content1 = do { open my $fh, '<', $file1 or die $!; local $/; <$fh>; };
while ( $content1 =~ /LONG_REGEX_WITH_TWO_CAPTURING_GROUPS/g )
print "$2 - ";
my $content2 = do { open my $fh, '<', "../../VT/$1" or die $!; local $/; <$fh>; };
while ( $content2 =~ /SECOND_REGEX/g ) {
print "$1\n\n<br/>"; # There is just one capturing group.
}
}
【问题讨论】:
-
我的意思是,这工作
perl -0777 -ne 'while(m/LONG_REGEX_WITH_TWO_CAPTURING_GROUPS/g";}'但我有两个文件,我需要更多代码才能获得所需的结果。 -
我建议在匹配成功后立即添加一行
my ($filename, $letter) = ($1,$2);。当您添加修改$1和$2的代码时,这可以避免出现意外错误。在你做任何其他事情之前保存这两个值,以确保它们不会被破坏。当然,open $fh, '<', $filename也一样会更清楚。 -
@doqx 你能展示你匹配的样本(字符串)吗?它会减少这里的可能性:)(见我的回答——有很多方法可以做到这一点)