我是Perl初学者,我有以下问题
如何使用Perl正则表达式通过关键字匹配最短的内容?例如:
my $txt='RMS Power : [ 0.00]>[ 2.83]<[ 4.00]dBm [PASS]';我希望得到以下结果:
$1: RMS Power
$2: 0.00
$3: 2.83
$4: 4.00
$5: dBm我的代码:
my $txt='RMS Power : [ 0.00]>[ 2.83]<[ 4.00]dBm [PASS]';
$re='.*?(\[([^\]]+)\]).*?(\[([^\]]+)\]).*?(\[([^\]]+)\])';
if ($txt =~ m/$re/is)
{
$sbraces1=$1;
$sbraces2=$2;
$sbraces3=$3;
$sbraces4=$4;
$sbraces5=$5;
print "$sbraces1 $sbraces2 $sbraces3 $sbraces4 $sbraces5 \n";
}上面是我的代码,输出是“0.00 0.00 2.83 2.83 4.00 ",我还想得到”RMS Power“,”dBm“字符串。
如果你能给我一些建议,我将不胜感激。
发布于 2017-08-10 23:34:05
发布于 2017-08-10 23:36:42
试试这段代码。
my $txt='RMS Power : [ 0.00]>[ 2.83]<[ 4.00]dBm [PASS]';
$re='(.*)\s*:\s*\[\s*(.*)\]>\[\s*(.*)\]<\[\s*(.*)\](.*)\[.*\]';
if ($txt =~ m/$re/is)
{
$sbraces1=$1;
$sbraces2=$2;
$sbraces3=$3;
$sbraces4=$4;
$sbraces5=$5;
print "$sbraces1 $sbraces2 $sbraces3 $sbraces4 $sbraces5 \n";
}发布于 2017-08-10 23:45:26
use Modern::Perl;
use Data::Dumper;
my $re = qr/^(.+?)\s+:\s+\[\s*(\S+?)\]>\[\s*(\S+?)\]<\[\s*(\S+?)\](\S+)/;
my $txt='RMS Power : [ 0.00]>[ 2.83]<[ 4.00]dBm [PASS]';
my @results = $txt =~ $re;
say Dumper\@results;输出:
$VAR1 = [
'RMS Power',
'0.00',
'2.83',
'4.00',
'dBm'
];正则表达式解释:
^ : start of string
(.+?) : group 1, 1 or more any character, not greedy
\s+ : 1 or more spaces
: : semicolon
\s+ : 1 or more spaces
\[\s* : open bracket followed by 0 or more spaces
(\S+?) : group 2, 1 or more non space, not greedy
\]>\[\s* : close bracket, greater than, open bracket, 0 or more spaces
(\S+?) : group 3, 1 or more non space, not greedy
\]>\[\s* : close bracket, greater than, open bracket, 0 or more spaces
(\S+?) : group 4, 1 or more non space, not greedy
\] : close bracket
(\S+) : group 5, 1 or more non spacehttps://stackoverflow.com/questions/45617057
复制相似问题