Perl -以逗号分隔字符串,忽略空格

mutmk8jj  于 2022-11-15  发布在  Perl
关注(0)|答案(2)|浏览(184)

我有这样的字符串:

$str="     a, b,    c>d:e,  f,    g ";

此字符串中可能有空格和/或制表符
我用perl拆分字符串:

my (@COLUMNS) = split(/[\s\t,]+/, $str));

但这会在位置[0]中创建前导空格。

@COLUMNS=[

    a
    b
    c>d:e
    f
    g
]

我想要这个:

@COLUMNS=[
    a
    b
    c>d:e
    f
    g
]
hsgswve4

hsgswve41#

我建议您使用全局正则表达式匹配来查找所有既不是逗号也不是空格的字符子序列
它将生成与split(/[\s\t,]+/相同的输出。(注意,\t是多余的,因为\s也匹配制表符。)但是将创建一个没有任何空元素的列表

use strict;
use warnings 'all';

my $str = "     a, b,    c>d:e,  f,    g ";

my @columns = $str =~ /[^\s,]+/g;

use Data::Dump;
dd \@columns;

输出

["a", "b", "c>d:e", "f", "g"]

***请注意,***就像您的split一样,此方法将忽略任何空字段:类似a,,,b的语句将返回[ 'a', 'b' ]而不是[ 'a', '', '', 'b' ]。另外,包含空格的列将被拆分,因此a,two words,b将生成[ 'a', 'two', 'words', 'b' ]而不是[ 'a', 'two words', 'b' ]。只有您才能判断是否可能出现这些情况

如果此方法有可能产生错误的结果,则最好简单地按逗号拆分并编写子例程来修剪结果字段

use strict; 
use warnings 'all';

sub trim(;$);

my $str="     a  ,, ,two words ,,, b";
my @columns = map trim, split /,/, $str;

use Data::Dump;
dd \@columns;

sub trim(;$) {
    (my $trimmed = $_[0] // $_) =~ s/\A\s+|\s+\z//g;
    $trimmed;
}

输出

["a", "", "", "two words", "", "", "b"]
e0bqpujr

e0bqpujr2#

一个很常见的解决方案是转换split返回的值。在这种情况下,你想删除任何前导或尾随空格,通常称为 trim 操作。使用这种方法,你根本不必担心split操作中的空格:

use strict; 
use warnings; 

my $str="     a, b,    c>d:e,  f,    g ";
my @columns = map { s/^\s*|\s*$//gr } split(/,/, $str);
print join(',', @columns), "\n";

@toolic上面提到的另一个解决方案是事先删除所有空格:

use strict; 
use warnings; 

my $str="     a, b,    c>d:e,  f,    g ";
$str =~ s/\s+//g; # remove all occurrences of 1 or more spaces
my @columns = split(/,/, $str);
print join(',', @columns), "\n";

上述两种解决方案都返回以下输出:
a、B、c〉d:e、f、g
有关/r修饰符的详细信息:
/r是一个修饰符,可以应用于非破坏性的替换。这意味着原始字符串不被修改,而是创建、修改并返回。这有很多优点,因为通常在标量上下文中,s///运算符将返回发生的替换次数,而不是修改后的字符串。这只在Perl版本〉= 5.14中可用。以下Perl版本的等效语句为:

my $original = "some_string";
(my $copy = $original) =~ s/$search_pattern/$replace_pattern/;

并在Map中使用:

map { 
   (my $temp = $_) =~ s/$search_pattern/$replace_pattern/; $temp 
} split /$delimiter/, $original;

例如:

my $string = 'abc'; 
my $num_substitutions = $string =~ s/a/d/; # 1 

my $string = 'abc';
my $new_string = $string =~ s/a/d/r; # dbc

相关问题