[英]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.