perl -->在一行中存在的多个元字符之间打印字符 [英] perl --> printing characters in between the multiple metacharacters present in a single line

查看:43
本文介绍了perl -->在一行中存在的多个元字符之间打印字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试一个脚本来找出元字符|"之间的字符.我试图获得第一个和随后的|"的位置元字符并尝试打印这两个位置之间的字符串.下面是我试过的代码:

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:

文件:|A|乙|计数|D|E|

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

预期输出: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";
}
}
}

推荐答案

使用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;

输出:

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

<小时>

使用正则匹配:


Using a regex match:

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

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

say "<$_>" for @fields;

输出:

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

<小时>

使用正则表达式匹配(替代):


Using a regex match (alternative):

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

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

输出:

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

这篇关于perl -->在一行中存在的多个元字符之间打印字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆