gpt4 book ai didi

Perl-如何在每个大写字母之前插入空格(第一次出现或现有的除外)?

转载 作者:行者123 更新时间:2023-12-02 08:56:32 25 4
gpt4 key购买 nike

我有一个像这样的字符串:

 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 走向答案的绿洲。

好的,根据下面的输入,我现在有:

$camel =~ s/([A-Z])/ $1/g;
$camel =~ s/^ //; # Strip out starting whitespace
$camel =~ s/([^[:space:]]+)/\u$1/g;

这可以完成但似乎有点过分了。不过可以。

最佳答案

s/(?<!^)[A-Z][a-z]*+(?!\s+)\K/ /g;

还有更少的“去他妈的废话”版本:

s/
(?<!^) #Something not following the start of line,
[A-Z][a-z]*+ #That starts with a capital letter and is followed by
#Zero or more lowercased letters, not giving anything back,
(?!\s+) #Not followed by one or more spaces,
\K #Better explained here [1]
/ /gx; #"Replace" it with a space.

编辑:我注意到,当您在混合中添加标点符号时,这也会添加额外的空格,这可能不是OP想要的;值得庆幸的是,解决方法只是将负面展望从\s+ 更改为\W+。尽管现在我开始想知道为什么我实际上添加了这些优点。德拉茨,我!

EDIT2:呃,抱歉,最初忘记了/g 标志。

EDIT3:好吧,有人否决了我。我变得迟钝了。不需要对 ^ 进行消极的回顾 - 我真的在这个问题上失败了。希望修复:

s/[A-Z][a-z]*+(?!\W)\K/ /gx;

1:http://perldoc.perl.org/perlre.html

关于Perl-如何在每个大写字母之前插入空格(第一次出现或现有的除外)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4434439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com