Perl移除字符串中的空格


主要有三种情形:空格在串首、串多处(所有空格)、串尾,需要针对这三种情形分别处理,这里所讲的空格包括(space、\s、\t、制表符)。
Perl trim function to strip whitespace from a string.
#移除所有空格
sub trim($);
#移除左(串首)空格
sub ltrim($);
#移除右(串尾)空格
sub rtrim($);
remove first and last character of string by substr
使用substr函数来移除字符串的首尾字符
To remove the first character of $str: substr($str, 0, 1, '')
移除字串$str的首字符
To remove the last character of $str: substr($str, -1, 1, '')
Or remove the last character of $str: substr($str, length($str)-1, 1, '')
移除字串$str的尾字符,当然还是chop函数是最佳的。下面我们来看正则版本的操作过程。
# Create a test string
my $string = " \t Hello world! ";
print trim($string)."\n";
print ltrim($string)."\n";
print rtrim($string)."\n";
# Perl trim function to remove whitespace from the start and end of the string
sub trim($){
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}
# Left trim function to remove leading whitespace
sub ltrim($){
my $string = shift;
$string =~ s/^\s+//;
return $string;
}
# Right trim function to remove trailing whitespace
sub rtrim($){
my $string = shift;
$string =~ s/\s+$//;
return $string;
}
If your white space is just spaces, then the following code will remove all spaces:
$mystring =~ tr/ //ds;
如果只是想移除首尾的空格,可按如下操作:
$string =~ s/^\s+|\s+$//g;
另外,Perl的CPAN上有此类功能的模块,可以自行搜索,这里推荐使用perl5i。
使用正则表达式分两步走:
先去掉前面的: $a=~s/^ +//;
在去掉后面的: $a=~s/ +$//;
一步就可以:
s/(^s+|s+$)//g;
s/\A\s+|\s+\z//g;
删除字符串末尾的换行:
chomp函数通常会删除变量里包含的字符串尾部的换行符。它是chop函数的一个略微安全些的版本,因为它对没有换行符的字符串没有影响。更准确地说,它根据了解$/的当前值删除字符串终止符,而不只是最后一个字符。和chop不同,chomp返回删除的字符数量。具体使用请参考这里。
Perl trim function to strip whitespace from a string.
#移除所有空格
sub trim($);
#移除左(串首)空格
sub ltrim($);
#移除右(串尾)空格
sub rtrim($);
remove first and last character of string by substr
使用substr函数来移除字符串的首尾字符
To remove the first character of $str: substr($str, 0, 1, '')
移除字串$str的首字符
To remove the last character of $str: substr($str, -1, 1, '')
Or remove the last character of $str: substr($str, length($str)-1, 1, '')
移除字串$str的尾字符,当然还是chop函数是最佳的。下面我们来看正则版本的操作过程。
# Create a test string
my $string = " \t Hello world! ";
print trim($string)."\n";
print ltrim($string)."\n";
print rtrim($string)."\n";
# Perl trim function to remove whitespace from the start and end of the string
sub trim($){
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}
# Left trim function to remove leading whitespace
sub ltrim($){
my $string = shift;
$string =~ s/^\s+//;
return $string;
}
# Right trim function to remove trailing whitespace
sub rtrim($){
my $string = shift;
$string =~ s/\s+$//;
return $string;
}
If your white space is just spaces, then the following code will remove all spaces:
$mystring =~ tr/ //ds;
如果只是想移除首尾的空格,可按如下操作:
$string =~ s/^\s+|\s+$//g;
另外,Perl的CPAN上有此类功能的模块,可以自行搜索,这里推荐使用perl5i。
使用正则表达式分两步走:
先去掉前面的: $a=~s/^ +//;
在去掉后面的: $a=~s/ +$//;
一步就可以:
s/(^s+|s+$)//g;
s/\A\s+|\s+\z//g;
删除字符串末尾的换行:
chomp函数通常会删除变量里包含的字符串尾部的换行符。它是chop函数的一个略微安全些的版本,因为它对没有换行符的字符串没有影响。更准确地说,它根据了解$/的当前值删除字符串终止符,而不只是最后一个字符。和chop不同,chomp返回删除的字符数量。具体使用请参考这里。