[英]Regex to find the number of extra spaces, including trailing and leading spaces
我正在尝试计算多余的空格数,包括字符串中的尾部和前导空格。 那里有很多建议,但没有一个能完全正确地计数。
示例(_表示空格)
__this is a string__with extra spaces__
应该匹配5个额外的空格。
这是我的代码:
if (my @matches = $_[0] =~ m/(\s(?=\s)|(?<=\s)\s)|^\s|\s$/g){
push @errors, {
"error_count" => scalar @matches,
"error_type" => "extra spaces",
};
}
这个正则表达式的问题是它两次计数中间的空格。 但是,如果我取消了前瞻/后视匹配项之一,则如下所示:
$_[0] =~ m/\s(?=\s)|^\s|\s$/g
它不会在字符串的开头算两个额外的空格。 (我的测试字符串只能匹配4个空格。)
尝试
$_[0] =~ m/^\s|(?<=\s)\s|\s(?=\s*$)/g
这应该匹配
换句话说,对于您的示例,这是这三种情况中的每一种都将匹配的内容:
__this is a string _with extra spaces__
12 2 32
这也适用于所有空间的边缘情况:
_____
12222
此正则表达式应匹配所有不必要的单个空格
^( )+|( )(?= )|( )+$
要么
$_[0] =~ m/^( )+|( )(?= )|( )+$/g
您可以将空格更改为\\ s,但随后它也会计数制表符。
分解:
^( )+
匹配连接到行首的所有空格
( )(?= )
匹配后跟另一个空格的任何空格
( )+$
匹配连接到行尾的所有空格
使用三个简单的正则表达式(为了清楚起见,用下划线替换空格),您可以使用:
use strict;
use warnings;
my $str = "__this_is_a_string__with_extra_underscores__";
my $temp = $str;
$temp =~ s/^_+//;
$temp =~ s/_+$//;
$temp =~ s/__+/_/g;
my $num_extra_underscores = (length $str) - (length $temp);
print "The string '$str' has $num_extra_underscores extraunderscores\n";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.