如何使用 perl 正则表达式在模式匹配后提取后续单词?

How to extract a subsequent word after pattern match using perl regex?

文件中的示例行:

one two three uname whirlcano four five

我想从多个文件中提取用户名

foreach $file (@file_names)
{
    open(my $fh, '<:encoding(UTF-8)', $file)
    or die "Could not open file '$file' $!";

    while (my $row = <$fh>)
    {
        if($row =~  "uname")
        {
            #here I want to extract only the immediate word after "uname", which is "whirlcano" in the above example.
        }
    }
}

提前致谢。

您可以使用正则表达式捕获组来捕获用户名:

while (my $row = <$fh>) {
    chomp($row); # strip newline character

    # capture first group of word characters after uname and one or more spaces
    my ($username) = $row =~ m/uname\s+(\w+)/;
    ....
}

您可以将上面示例中的 \s+ 更改为您的文件具有的任何分隔符,但通常在使用 real CSV 解析器解析 CSV 类型文件时比常规解析器更好表达式。 Text::CSV_XS 就是这样一种流行的解析器。

有关在正则表达式中捕获组的更多信息,请参阅 perldoc perlre

的捕获组部分