regex 定位到包含单词“hello”的任何行开头的正则表达式,以确定它们在字符串中的出现顺序

nkcskrwz  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(99)

应该找到第一个hello,打印字符位置...找到下一个hello并打印字符位置...并且锚可以是具有第一个hello的任何行...
为什么不管用?
尝试#1:

$line = "\n hi\n   hiya \n   hello\n hi \n hello2";
$match = $line =~ m/^\s*(hello)/;
if (!$match) {
    die("not found\n");
}

print "found at pos: " . pos($line) . "\n";
$line = $';
$match = $line =~ m/^\s*(hello)/;
if (!$match) {
    die("not found\n");
}
print "found at pos: " . pos($line) . "\n";

结果:not found
尝试#2:

$line = "\n hi\n   hiya \n   hello\n hi \n hello2";
$match = $line =~ m/\A\s*(hello)/;
if (!$match) {
    die("not found\n");
}

$line = $';
$match = $line =~ m/\A\s*(hello)/;
if (!$match) {
    die("not found\n");
}
print "found at pos: " . pos($line) . "\n";

结果:not found

kokeuurv

kokeuurv1#

对于“多行”字符串,需要/m修饰符,以便^匹配字符串内的行开头

use warnings;
use strict;
use feature 'say';

my $line = "\n hi\n   hiya \n   hello\n hi \n hello2";

while ( $line =~ /^\s*(hello)/mg ) { 
    say $1; 
    say pos $line 
}

打印

hello
22
hello
34

相关问题