Perl-如何在每个大写字母之前插入空格(第一次出现或现有的除外)?
我有一个像这样的字符串:
SomeCamel WasEnteringText
我找到了各种分割字符串并使用 php str_replace 插入空格的方法,但是,我在 perl 中需要它。
有时字符串前面可能有空格,有时则没有。有时字符串中会有空格,但有时则没有。
我尝试过:
my $camel = "SomeCamel WasEnteringText";
#or
my $camel = " SomeCamel WasEntering Text";
$camel =~ s/^[A-Z]/\s[A-Z]/g;
#and
$camel =~ s/([\w']+)/\u$1/g;
以及=~s//g的更多组合;经过大量阅读后。
我需要一位大师来引导这只骆驼走向答案的绿洲。
好的,根据下面的输入,我现在得到了:
$camel =~ s/([A-Z])/ $1/g;
$camel =~ s/^ //; # Strip out starting whitespace
$camel =~ s/([^[:space:]]+)/\u$1/g;
这可以完成但似乎过多。不过有效。
I have a string like:
SomeCamel WasEnteringText
I have found various means of splitting up the string and inserting spaces with php str_replace but, i need it in perl.
Sometimes there may be a space before the string, sometimes not. Sometimes there will be a space in the string but, sometimes not.
I tried:
my $camel = "SomeCamel WasEnteringText";
#or
my $camel = " SomeCamel WasEntering Text";
$camel =~ s/^[A-Z]/\s[A-Z]/g;
#and
$camel =~ s/([\w']+)/\u$1/g;
and many more combinations of =~s//g; after much reading.
I need a guru to direct this camel towards an oasis of answers.
OK, based on the input below I now have:
$camel =~ s/([A-Z])/ $1/g;
$camel =~ s/^ //; # Strip out starting whitespace
$camel =~ s/([^[:space:]]+)/\u$1/g;
Which gets it done but seems excessive. Works though.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
还有更少的“拧这个胡言乱语”的版本:
编辑:我注意到,当你在混合中添加标点符号时,这也会增加额外的空白,这可能不是OP想要的;值得庆幸的是,解决方法只是将负面展望从 \s+ 更改为 \W+。尽管现在我开始想知道为什么我实际上添加了这些优点。德拉茨,我!
EDIT2:呃,抱歉,最初忘记了 /g 标志。
EDIT3:好吧,有人否决了我。我变得迟钝了。不需要对 ^ 进行消极的回顾 - 我真的在这个问题上失败了。希望修复:
1:http://perldoc.perl.org/perlre.html
And the less "screw this horsecrap" version:
EDIT: I noticed that this also adds extra whitespace when you add punctuation into the mix, which probably isn't what the OP wants; thankfully, the fix is simply changing the negative look ahead from \s+ to \W+. Although now I'm beginning to wonder why I actually added those pluses. Drats, me!
EDIT2: Erm, apologies, originally forgot the /g flag.
EDIT3: Okay, someone downvote me. I went retarded. No need for the negative lookbehind for ^ - I really dropped the ball on this one. Hopefully fixed:
1: http://perldoc.perl.org/perlre.html
尝试:
请注意
$camel =~ s/([^ ])([AZ])/$1 $2/g;
的明显尝试有一个错误:如果有大写字母依次排列(例如“ABCD”将转换为“ABCD”而不是“ABC D”)Try:
Please note that the obvious try of
$camel =~ s/([^ ])([A-Z])/$1 $2/g;
has a bug: it doesn't work if there are capital letters following one another (e.g. "ABCD" will be transformed into "ABCD" and not "A B C D")尝试 :
s/(?<=[az])(?=[AZ])/ /g
这将在小写字符之后(即不是空格或字符串开头)和大写字符之前插入空格。
Try :
s/(?<=[a-z])(?=[A-Z])/ /g
This inserts as space after a lower case character (ie not a space or start of string) and before and upper case character.
改进……
在 Hughmeir 上,这也适用于以小写字母开头的数字和单词。
测试
Improving ...
... on Hughmeir's, this works also with numbers and words starting with lower-case letters.
Tests