我有一个字符串:
1 Vectorial position [X Y] X 682.9 1.0 -1.0 X 682.6 X -0.3 ----.-----
在此字符串中,有一些空格将被用于拆分字符串的任何特殊字符替换。
必需的输出是:
1 ~ Vectorial position [X Y] ~ X ~ 682.9 ~ 1.0 ~ -1.0 ~ X ~ 682.6 ~ X ~-0.3 ~ ----.-----****
对于上面我尝试过使用:
$yval_arr[$i] =~s/ /~/g;
$yval_arr[$i] =~ s/(.)\1\1+/$1$1$1/g;
$yval_arr[$i] =~s/(.)\1{1,}/$1$1$1/g;
但使用此字符时,第一个字符会重复2次,即如果它在开始时为11
,则变为111
。
请帮忙。
答案 0 :(得分:0)
my $str = "1 Vectorial position [X Y] X 682.9 1.0 -1.0 X 682.6 X -0.3 ----.-----";
# first insert ~ before all X with leading space char
$str =~ s/( X)/ ~$1/g;
# replace all numbers with numbers + ~
$str =~ s/([- ]\d+\.\d+)/ ~ $1/g;
# replace the first space with " ~ "
$str =~ s/ / ~ /;
答案 1 :(得分:0)
我会在空格上拆分原始字符串,然后进行一些创意字段提取:我假设字符串中的第一个单词和最后9个单词是单独的字段,剩下的是成为输出中的第二个字段
$str = "1 Vectorial position [X Y] X 682.9 1.0 -1.0 X 682.6 X -0.3 ----.-----";
@words = split ' ', $str;
@fields = splice @words, -9;
$first = shift @words;
unshift @fields, $first, join(" ", @words);
say join(" ~ ", @fields);
1 ~ Vectorial position [X Y] ~ X ~ 682.9 ~ 1.0 ~ -1.0 ~ X ~ 682.6 ~ X ~ -0.3 ~ ----.-----
答案 2 :(得分:-1)
我会将您的数据拆分为描述和数据,然后对数据进行操作。这使得理解和调试更容易。
#!/usr/bin/perl
use warnings;
use strict;
my $str = '1 Vectorial position [X Y] X 682.9 1.0 -1.0 X 682.6 X -0.3 ----.-----';
my ($description, $data) = $str =~ m|^(.*\])(.*)$|; # $1 - everything upto [X Y]
# $2 - everything else
$data =~ s|\s+| ~ |g; # Replace one or more spaces with space-tilda-space everywhere
$description =~ s|^(\d+)(\s+)|$1 ~ |; # Likewise in description, between number and label
my $result = join '', $description, $data;
print "BEFORE '$str'\n";
print "AFTER '$result'\n";
输出:
BEFORE '1 Vectorial position [X Y] X 682.9 1.0 -1.0 X 682.6 X -0.3 ----.-----'
AFTER '1 ~ Vectorial position [X Y] ~ X ~ 682.9 ~ 1.0 ~ -1.0 ~ X ~ 682.6 ~ X ~ -0.3 ~ ----.-----'
如果我们将$str
更新为:
my $str = '1 Vectorial position [Z] Z 267.0 1.0 -1.0 Z 267.3 Z 0.3 -----.-*---';
输出结果为:
BEFORE '1 Vectorial position [Z] Z 267.0 1.0 -1.0 Z 267.3 Z 0.3 -----.-*---'
AFTER '1 ~ Vectorial position [Z] ~ Z ~ 267.0 ~ 1.0 ~ -1.0 ~ Z ~ 267.3 ~ Z ~ 0.3 ~ -----.-*---'