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

Bil*_*ore 2 regex perl

应该找到第一个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";
Run Code Online (Sandbox Code Playgroud)

结果: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";
Run Code Online (Sandbox Code Playgroud)

结果:not found

zdi*_*dim 7

对于“多行”字符串需要/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 
}
Run Code Online (Sandbox Code Playgroud)

印刷

hello
22
hello
34
Run Code Online (Sandbox Code Playgroud)