perl --> printing characters in between the multiple metacharacters present in a single line

血红的双手。 提交于 2021-01-29 10:14:51

问题


I am trying a script to find out the characters between the metacharacter "|". I tried to get the position of the first and the succeeding "|" metacharacter and tried to print the string between those two positions. Below is the code I tried:

File : | A| B| Count| D| E|

Expected output : A B Count D E

if($line =~ /\|/) 
{
while ($line =~ m/\|/g) 
{
my $start_pos = $-[0]; 
my $end_pos = $+[0]; 
my $hit_pos = "$start_pos - $end_pos";
my $char = substr($line, $start_pos, $end_pos);
if($char =~/\w/){
  print "$char\n";
}
}
}

回答1:


Using split:

my $line = '| A| B| Count| D| E|';

my @fields = split(/\|/, $line, -1);
shift(@fields);  # Ignore stuff before first "|"
pop(@fields);    # Ignore stuff after last "|"

say "<$_>" for @fields;

Output:

< A>
< B>
< Count>
< D>
< E>

Using a regex match:

my $line = '| A| B| Count| D| E|';

my @fields = $line =~ / \| ([^|]*) (?=\|) /xg;

say "<$_>" for @fields;

Output:

< A>
< B>
< Count>
< D>
< E>

Using a regex match (alternative):

my $line = '| A| B| Count| D| E|';

while ($line =~ / \| ([^|]*) (?=\|) /xg) {
   say "<$1>";
}

Output:

< A>
< B>
< Count>
< D>
< E>



回答2:


The easiest thing to do would probably be to just delete the pipes.

$line =~ s/\Q|\E//g;


来源:https://stackoverflow.com/questions/59895806/perl-printing-characters-in-between-the-multiple-metacharacters-present-in-a

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!