【问题标题】:How to extract a substring in perl如何在perl中提取子字符串
【发布时间】:2016-03-30 21:17:58
【问题描述】:

我是 perl 新手,需要你的帮助。

我正在读取目录中文件的内容。 我需要从包含*.dat的文件中提取子字符串@

示例字符串:

1) # **   Template Name: IFDOS_ARCHIVE.dat

2) # **  profile for IFNEW_UNIX_CMD.dat template  **

3) # ** Template IFWIN_MV.dat **

需要提取:

1) IFDOS_ARCHIVE.dat

2) IFNEW_UNIX_CMD.dat

3) IFWIN_MV.dat

我的代码:

if(open(my $jobprofile, "./profiles/$vitem[0].profile")) {
   my @jobprofiletemp = <$jobprofile>;
   close($jobprofile);
   @proftemplates = grep /.dat/,@jobprofiletemp;

   my $strproftemp = $proftemplates[0];
   my ($tempksh) = $strproftemp =~ / ([^_]*)./;
   print "tempksh: $tempksh","\n";
} else { warn  "problem opening ./$_\n\n"; }

我的正则表达式不工作。 你有什么建议?

【问题讨论】:

标签: regex perl


【解决方案1】:

我认为你会更好:

while (<$jobprofile>) {
  if ( /(\S+)\.dat/ ) {
    print "$1\n";
  }
}

while 是为了确保您解析每一行)

正则表达式查找一系列非空白字符 (\S),后跟 .dat

\S+ 周围的括号将该部分的匹配捕获到特殊变量 $1

【讨论】:

  • 感谢您的回答。我尝试了你的正则表达式,我得到了没有.dat 的正确子字符串。我可以在代码的后半部分连接 .dat。
  • 我以为你不需要.dat。如果需要,可以将) 移动到.dat 之后,如/(\S+\.dat)/。括号将匹配项捕获到特殊变量中。
【解决方案2】:

试试这个

open my $fh,"<","file.txt";

while (<$fh>)
{   
    next if /^\s+/; #skip the loop for empty line 
    ($match) = /\s(\w+\.dat)/g; # group the matching word and store the input into the $match
    print "$match\n";
}

或者干脆试试 perl one liner

perl -ne'    print $1,"\n" if (m/(\w+\.dat)/)    ' file.txt

或者你正在使用 linux 尝试使用 linux 命令来进行操作

grep -ohP '\w+\.dat' one.txt

o 只显示匹配的元素

h 用于显示不带文件名的输出

P 用于 perl 正则表达式

【讨论】:

  • 感谢您的回答。我尝试了 $match 的正则表达式,它工作得很好。
猜你喜欢
  • 1970-01-01
  • 2010-11-29
  • 1970-01-01
  • 1970-01-01
  • 2011-11-17
  • 1970-01-01
  • 1970-01-01
  • 2014-09-23
相关资源
最近更新 更多