删除单个字母之间的空格 [英] Removing spaces between single letters
问题描述
我有一个字符串,它可能包含任意数量的由空格分隔的单字母.我正在寻找一个正则表达式(在 Perl 中),它将删除所有(未知数量)单个字母之间的空格.
I have a string that may contain an arbitrary number of single-letters separated by spaces. I am looking for a regex (in Perl) that will remove spaces between all (unknown number) of single letters.
例如:
ab c d
应该变成 ab cd
a bcd e f gh
应该变成 a bcd ef gh
a b c
应该变成 abc
和
abc d
应该保持不变(因为没有单个字母后跟或前面有单个空格).
abc d
should be unchanged (because there are no single letters followed by or preceded by a single space).
感谢您的任何想法.
推荐答案
您的描述与示例不符.在我看来,您想删除以下任何空格:(1) 前面不是一个字母,并且 (2) 后面是一个字母,而这个字母本身不是一个字母.这些条件可以精确地表示为嵌套环视:
Your description doesn't really match your examples. It looks to me like you want to remove any space that is (1) preceded by a letter which is not itself preceded by a letter, and (2) followed by a letter which is not itself followed by a letter. Those conditions can be expressed precisely as nested lookarounds:
/(?<=(?<!\pL)\pL) (?=\pL(?!\pL))/
已测试:
use strict;
use warnings;
use Test::Simple tests => 4;
sub clean {
(my $x = shift) =~ s/(?<=(?<!\pL)\pL) (?=\pL(?!\pL))//g;
$x;
}
ok(clean('ab c d') eq 'ab cd');
ok(clean('a bcd e f gh') eq 'a bcd ef gh');
ok(clean('a b c') eq 'abc');
ok(clean('ab c d') eq 'ab cd');
输出:
1..4
ok 1
ok 2
ok 3
ok 4
我假设您的意思是一个空格字符 (U+0020);如果你想匹配任何空格,你可能想用 \s+
替换空格.
I'm assuming you really meant one space character (U+0020); if you want to match any whitespace, you might want to replace the space with \s+
.
这篇关于删除单个字母之间的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!