好的,我正在尝试使用正则表达式从字符串的开头删除一个非常顽固的空格。 使用 Text:CSV 模块将此字符串从 CSV 文件解析为 Perl,当我打印字符串的 Dumper 时,我得到:
$VAR1 = ' Mgmt-General-Other';
现在我尝试使用 Regex 来删除这个空格,有人会告诉我使用:
$string =~ s/\s+$//;
我已经尝试过这个以及:
$string =~ s/\s//g;
和
$string =~ s/^\s//g;
但这些都不起作用,中间的那个把所有空间都拉了出来,除了我想要的那个。我试图遍历一个 2,000 行的 CSV 文件,所以我宁愿让它自动化,而不必为这个奇怪的实例做一个特例。
有没有办法让这个开头的字符不是空格或空格?或者我怎样才能把它取出来?
添加更多我尝试过的东西;
$string =~ s/^\s+//;
这是我的代码:
my @value = @columns[1..12];
my $string = @value[9];
$string =~ s/^\s+//;
$string =~ s/\s+$//;
print Dumper $string;
如果重要的话,这些是我在脚本顶部的声明:
use strict;
use DBI;
use Getopt::Long;
use Spreadsheet::WriteExcel;
use Spreadsheet::WriteExcel::Utility;
use Data::Dumper;
use Text::CSV;
最佳答案
您实际上非常接近,因为在字符串的开头替换空格的正确正则表达式是:
$sting =~ s/^\s+//;
至于其他解决方案:
$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.
更新:原来你的字符串中有一个 \xA0
(所谓的“不可破坏的空格”,它不包含在 \s
中)。 )试试这个:
$sting =~ s/^[\s\xA0]+//;
关于regex - 删除 perl 正则表达式中顽固的第一个字符串空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11512264/