简体   繁体   English

如何搜索并用正则表达式替换并在Perl中保留空格?

[英]How do I search and replace with a regex and preserve blank spaces in Perl?

I'm using this code: $text =~ s/\\s(\\w)/\\u$1/g; 我正在使用此代码: $text =~ s/\\s(\\w)/\\u$1/g;

But This is an example 但这This is an example

Become ThisIsAnExample 成为这是一个ThisIsAnExample

Instead of This Is An Example . 代替This Is An Example

How to preserve blank spaces? 如何保留空格?

Use lookbehind. 使用后向。

$text =~ s/(?<!\S)(\w)/\u$1/g;

Or use the more efficient \\K (Perl 5.10+). 或使用效率更高的\\K (Perl 5.10+)。

$text =~ s/(?:^|\s)\K(\w)/\u$1/g;

Both of the solutions will make sure the first word is capitalized too. 两种解决方案都将确保第一个单词也大写。 If that's not an issue, the second solution can be simplified to the following: 如果这不是问题,可以将第二种解决方案简化为以下内容:

$text =~ s/\s\K(\w)/\u$1/g;

The matching contains the whitespace, the replacement doesn't. 匹配项包含空格,替换项不包含空格。

$text =~ s/(\s)(\w)/$1\u$2/g;

Since \\s contains different types of whitespace characters, if you want to keep it in your replacement, you need to capture it and put it back. 由于\\s包含不同类型的空格字符,因此,如果要将其保留在替换中,则需要捕获并将其放回去。

An alternative is to use word boundaries and full "words". 另一种选择是使用单词边界和完整的“单词”。

$text =~ s/\b(\w+)\b/\u$1/g;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM