gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:26:06 27 4
gpt4 key购买 nike

应该首先找到 hello,打印字符位置...找到下一个 hello 并打印字符位置... anchor 可以是具有第一个 你好...

为什么它不起作用?

尝试 #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";

结果:未找到

尝试#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";

结果:未找到

最佳答案

对于“多行”字符串需要/m modifier ^ 匹配字符串中的行开头

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

关于regex - 正则表达式锚定到包含单词 "hello"的任何行的开头,以便它们在字符串中出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74466593/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com