[英]How to extract a subsequent word after pattern match using perl regex?
Sample line from a file: 文件中的示例行:
one two three uname whirlcano four five
I want to extract the user names from multiple files 我想从多个文件中提取用户名
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.
}
}
}
Thanks in advance. 提前致谢。
You can use a regular expression capturing group to capture the username: 您可以使用正则表达式捕获组来捕获用户名:
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+)/;
....
}
You can change \\s+
in the above example to whatever delimiter your file has, but typically when parsing CSV type files using a real CSV parser is better than regular expressions. 您可以在上面的示例中将
\\s+
更改为文件具有的任何定界符,但是通常,当使用真正的 CSV解析器解析CSV类型的文件时,比使用正则表达式更好。 Text::CSV_XS
is one such parser that is popular. Text::CSV_XS
是一种流行的解析器。
For more information about capturing groups in regular expressions, please refer to the Capture Groups section of perldoc perlre
有关在正则表达式中捕获组的更多信息,请参考
perldoc perlre
的“捕获组”部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.