[英]Search and replace string of certain length using Perl regex
I am trying to search and replace a string that is up to and including 3 characters in length with nothing (so 'deleting' the element contents). 我试图搜索并替换长度为3个字符的字符串,没有任何东西(所以'删除'元素内容)。
So I have something like: 所以我有类似的东西:
foreach (@array) {
s/^{1,3}$//;
}
Eg 例如
@array = ('one', 'two', 'three', 'four', 'five', 'six', 'seven');
So when printing, expected output would be: 因此,在打印时,预期输出将是:
result: result: result: three result: four result: five result: result: seven
So for the affected inputs, the output would be an 'empty place'. 因此,对于受影响的输入,输出将是“空位”。
This at the moment doesn't happen... I'm betting I'm making a simple mistake due to my still-shaky understanding of regex. 目前这还没有发生......我打赌我犯了一个简单的错误,因为我对正则表达式的理解仍然不稳定。 Any help appreciated!
任何帮助赞赏!
If there is a simple way to actually remove the element totally without creating a new array, that would also be useful to know. 如果有一种简单的方法可以在不创建新数组的情况下完全删除元素,那么知道这一点也很有用。
If you want to match any three characters, s/^.{1,3}$//
should work. 如果你想匹配任何三个字符,
s/^.{1,3}$//
应该可以工作。 I just added a dot after the ^
, as your original regex didn't specify what kind of character you wanted to match 1-3 of. 我刚刚在
^
之后添加了一个点,因为你的原始正则表达式没有指定你想要匹配的1-3个字符。
Probably s/^\\w{1,3}$//;
可能
s/^\\w{1,3}$//;
You are forgetting \\w
to group it with {1,3}
你忘记
\\w
将它与{1,3}
分组
Simple regex problem aside, you can use grep
to select the elements you want: 除了简单的正则表达式问题,您可以使用
grep
选择所需的元素:
@array = grep { !/^.{1,3}$/ } @array;
Then just print the results: 然后只打印结果:
print "Result: $_\n" foreach @array;
Results: 结果:
Result: three
Result: four
Result: five
Result: seven
The way I read your question is that you want to actually modify the array's contents. 我读你的问题的方式是你想要实际修改数组的内容。 You could use splice thusly:
你可以这样使用拼接 :
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
my @array = qw(one two three four five six seven);
my $i = 0;
for (@array) {
m/^\w{1,3}$/ && splice(@array, $i, 1, undef);
$i++;
}
print Dumper \@array;
print "\n";
for my $e (@array) {
print defined $e ? "result: $e " : "result: "
}
print "\n";
And when run: 运行时:
$VAR1 = [
undef,
undef,
'three',
'four',
'five',
undef,
'seven'
];
result: result: result: three result: four result: five result: result: seven
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.