删除perl正则表达式中顽固的第一个字符串空格

Nat*_*and 2 regex perl whitespace space

好的,我正在尝试使用正则表达式从字符串的开头删除一个非常顽固的空间.使用Text:CSV模块将此字符串从CSV文件解析为Perl,当我打印字符串的Dumper时,我得到:

$VAR1 = ' Mgmt-General-Other';  
Run Code Online (Sandbox Code Playgroud)

现在我已经尝试使用正则表达式来删除这个空间,有人会告诉我使用:

$string =~ s/\s+$//;
Run Code Online (Sandbox Code Playgroud)

我已经尝试过这个以及:

$string =~ s/\s//g;
Run Code Online (Sandbox Code Playgroud)

$string =~ s/^\s//g;
Run Code Online (Sandbox Code Playgroud)

并且这些都没有奏效,中间的一个从每个空间中拉出除了我想要的那个空间.我正在尝试遍历一个2,000行的CSV文件,所以我宁愿让它自动化,而不必为这个奇怪的实例做一个特殊的情况.

有没有什么方法,这个角色在开始时不是空格或白色空间?或者我怎么能把它拿出来?

添加我尝试过的更多东西;

$string =~ s/^\s+//;
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

my @value = @columns[1..12];
my $string = @value[9];
$string =~ s/^\s+//;
$string =~ s/\s+$//;
print Dumper $string;
Run Code Online (Sandbox Code Playgroud)

如果重要,这些是我在脚本顶部的声明:

use strict;
use DBI;
use Getopt::Long;
use Spreadsheet::WriteExcel;
use Spreadsheet::WriteExcel::Utility;
use Data::Dumper;
use Text::CSV;
Run Code Online (Sandbox Code Playgroud)

rai*_*7ow 10

实际上你非常接近,因为在字符串开头替换空格的正确正则表达式是:

$sting =~ s/^\s+//;
Run Code Online (Sandbox Code Playgroud)

至于其他解决方案:

$sting =~ s/\s+$//; # the same as 'rtrim', removes whitespace at the end of the string
$sting =~ s/\s//g;  # will just remove all whitespace
$sting =~ s/^\s//g; # will remove single whitespace symbol right at the beginning of the string.
Run Code Online (Sandbox Code Playgroud)

更新:结果证明你的字符串中有一个\xA0(所谓的'不可破解的空格',它不包括在内\s).) 试试这个:

$sting =~ s/^[\s\xA0]+//;
Run Code Online (Sandbox Code Playgroud)

  • 然后,它可能不是一个空格......它可能是一个制表符. (2认同)