如何删除字符串中的空格?

问题描述 投票:0回答:12

我声明了一个变量

$myString
,其值为
'3 '
(注意空格)。 有没有函数可以去除返回值的空格? 有点像
SomeFun($myString)
然后返回
'3'
(没有空格)。

#!C:\Perl\bin\perl.exe
use strict;
use warnings;
use Data::Dumper; 
 
my $fh = \*DATA; 
 
print Dumper parse_constant_spec( $fh );      
 
# Parse a constant spec file. 
# Pass in a handle to process. 
# As long as it acts like a file handle, it will work. 
sub parse_constant_spec { 
    my $fh = shift; 
 
    my %spec; 
 
    # Until file is done: 
        # Read in a whole block 
    while( my $block = read_block($fh) ) { 
 
        # Parse the and return key/value pairs for a hash. 
        my %constant = parse_block( $block ); 
 
        # Store a ref to the hash in a big hash of all blocks, keyed by constant_name. 
        $spec{ $constant{const_name} } = \%constant; 
 
    } 
 
    # Return ref to big hash with all block data 
    return \%spec; 
} 
 
# Read a constant definition block from a file handle. 
# void return when there is no data left in the file. 
# Otherwise return an array ref containing lines to in the block.  
sub read_block { 
    my $fh = shift; 
 
    my @lines; 
    my $block_started = 0; 
 
    while( my $line = <$fh> ) { 
 
        $block_started++ if $line =~ /^constant/; 
 
        if( $block_started ) { 
 
            last if $line =~ /^\s*$/; 
 
            push @lines, $line; 
        } 
    } 
 
    return \@lines if @lines; 
 
    return; 
}      
 
sub parse_block { 
    my $block = shift; 
    my ($start_line, @attribs) = @$block; 
 
    my %constant; 
 
    # Break down first line: 
    # First separate assignment from option list. 
    my ($start_head, $start_tail) = split /=/, $start_line; 
 
    # work on option list 
    my @options = split /\s+/, $start_head; 
 
    # Recover constant_name from options: 
    $constant{const_name} = pop @options; 
    $constant{options} = \@options; 
 
    # Now we parse the value/type specifier 
    @constant{'type', 'value' } = parse_type_value_specifier( $start_tail ); 
 
    # Parse attribute lines. 
    # since we've already got multiple per line, get them all at once. 
    chomp @attribs; 
    my $attribs = join ' ', @attribs; 
 
    #  we have one long line of mixed key = "value" or key = <TYPE VALUE>  
 
    @attribs = $attribs =~ /\s*(\w+\s+=\s+\w+\s+|\w+\s+=\s+".*?"|\w+\s+=\s+<.*?>)\s*/g; 
 
    for my $attrib ( @attribs ) { 
        warn "$attrib\n"; 
        my ($name, $value) = split /\s*=\s*/, $attrib; 
 
        if( $value =~ /^"/ ) {  
            $value =~ s/^"|"\s*$//g; 
        } 
        elsif( $value =~ /^</ ) { 
           $value = [ parse_type_value_specifier( $start_tail ) ]; 
        } 
        else { 
            warn "Bad line"; 
        } 
 
        $constant{ $name } = $value; 
    } 
 
    return %constant; 
} 
 
sub parse_type_value_specifier { 
    my $tvs = shift; 
 
    my ($type, $value) = $tvs =~ /<(\w+)\s+(.*?)>/; 
 
    return $type, $value; 
} 
 
__DATA__ 
constant fixup GemEstabCommDelay = <U2 20> 
    vid = 6 
    name = "ESTABLISHCOMMUNICATIONSTIMEOUT" 
    units = "s" 
    min = <U2 0> 
    max = <U2 1800> 
    default = <U2 20> 
 
 
constant fixup private GemConstantFileName = <A "C:\\TMP\\CONST.LOG"> 
    vid = 4 
    name = ""  units = "" 
 
 
constant fixup private GemAlarmFileName = <A "C:\\TMP\\ALARM.LOG"> 
    vid = 0 
    name = "" 
    units = ""   

输出:

D:\learning\perl>hello1.pl
vid = 6
Bad line at D:\learning\perl\hello1.pl line 102, <DATA> line 8.
name = "ESTABLISHCOMMUNICATIONSTIMEOUT"
units = "s"
min = <U2 0>
max = <U2 1800>
default = <U2 20>
vid = 4
Bad line at D:\learning\perl\hello1.pl line 102, <DATA> line 13.
name = ""
units = ""
vid = 0
Bad line at D:\learning\perl\hello1.pl line 102, <DATA> line 18.
name = ""
units = ""
$VAR1 = {
          'GemAlarmFileName' => {
                                  'vid' => '0      ',
                                  'options' => [
                                                 'constant',
                                                 'fixup',
                                                 'private'
                                               ],
                                  'value' => '"C:\\\\TMP\\\\ALARM.LOG"',
                                  'name' => '',
                                  'type' => 'A',
                                  'const_name' => 'GemAlarmFileName',
                                  'units' => ''
                                },
          'GemEstabCommDelay' => {
                                   'vid' => '6      ',
                                   'options' => [
                                                  'constant',
                                                  'fixup'
                                                ],
                                   'value' => '20',
                                   'min' => [
                                              'U2',
                                              '20'
                                            ],
                                   'name' => 'ESTABLISHCOMMUNICATIONSTIMEOUT',
                                   'max' => [
                                              'U2',
                                              '20'
                                            ],
                                   'default' => [
                                                  'U2',
                                                  '20'
                                                ],
                                   'type' => 'U2',
                                   'units' => 's',
                                   'const_name' => 'GemEstabCommDelay'
                                 },
          'GemConstantFileName' => {
                                     'vid' => '4      ',
                                     'options' => [
                                                    'constant',
                                                    'fixup',
                                                    'private'
                                                  ],
                                     'value' => '"C:\\\\TMP\\\\CONST.LOG"',
                                     'name' => '',
                                     'type' => 'A',
                                     'const_name' => 'GemConstantFileName',
                                     'units' => ''
                                   }
        };

D:\learning\perl>

您可能会注意到

'vid' => '0      ',
(注意空白)

上面的代码来自答案。我正在研究。

perl
12个回答
28
投票
$myString =~ s/^\s*(.*?)\s*$/$1/;

这将修剪两侧的空白。

从右边开始:

$myString =~ s/\s*$//;

16
投票

如果您的空白只是空格,那么以下代码将删除所有空格:

$mystring =~ tr/ //ds;

11
投票
sub trim($)
{
    my $string = shift;
    $string =~ s/^\s+//;
    $string =~ s/\s+$//;
    return $string;
}


print trim($myString)

9
投票

试试这个:

# Delete leading/trailing whitespace.
$string =~ s/^\s+|\s+$//g;

5
投票

另一个潜在的替代解决方案是 CPAN 中的 Text::Trim,它将“从字符串中删除前导和/或尾随空格”。它有一个

trim
功能,可能会满足您的需求。


2
投票
sub trim
{
    my $str = $_[0];
    $str=~s/^\s+|\s+$//g;
    return $str;
}

print trim(" 4 ");

2
投票

这是一个子例程,可让您从字符串中删除前导和尾随空格,同时删除字符串中多余的空格并将其替换为单个空格。

-- routine

sub unspace { my @stringer = @_ ? @_ : $; $ = join( ' ', split(' ')) for @stringer; return wantarray ? @stringer : "@stringer"; }

-- usage

$MySpacedString = ' String with tabs double-spaces and other whitespace areas. '; $MyCleanString = unspace($MySpacedString);


2
投票

删除字符串中的所有空格:

$string =~ s/ //g;

1
投票

只是查看你的程序,我发现了 3 个可以改进或修复的地方。

如果我的代码格式不正确,我深表歉意。 :-(

在你的函数parse_block(...)中,有3项需要注意。

@attribs = $attribs =~ /\s*(\w+\s+=\s+\w+\s+|\w+\s+=\s+".*?"|\w+\s+=\s+<.*?>)\s*/g;

要消除 vid => '6 ' 之后的空格,只需不要在第一个子正则表达式末尾包含 \s+ 即可。

写为:

@attribs = $attribs =~ /\s*(\w+\s+=\s+\w+|\w+\s+=\s+".*?"|\w+\s+=\s+<.*?>)\s*/g;  

$value = [ parse_type_value_specifier( $start_tail ) ];  

你想要这个:

$value = [ parse_type_value_specifier( $value ) ]; 

(请注意,函数的参数应该是 $value 而不是 $start_tail。)您可能没有注意到这一点。

在 @attributes 的循环中,当“value”具有普通值(“value”中没有“”或 <...> 项)时,if/else 条件中的“else”就会执行。

更新:将

parse_type_value_specifier(...)
中的参数更改为 $value。它被(错误地)表述为 $attrib。


0
投票

从 Transact SQL 中的变量

$test (eq rtrim(ltrim(@sStr))
中删除空格:

$test =~s/^\s*(\S*)\s*$/$1/;

0
投票

如果您愿意使用 CPAN 模块,那么

String::Util
,或者更经济的
Text::Trim
将是可能的选择。

修剪琴弦是每个人都喜欢建造的自行车棚之一!请参阅 @szabgab 编写的简短 perlmaven 教程,了解 TIMTOWDI 乐趣的小样本。


0
投票

我建议您使用

Text::Trim
模块,它提供
ltrim
rtrim
trim
,所有这些都会修剪传递的参数,或者如果您不提供参数则使用
$_
。它不是核心模块,因此可能需要安装

© www.soinside.com 2019 - 2024. All rights reserved.