简体   繁体   中英

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;

But This is an example

Become ThisIsAnExample

Instead of 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+).

$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.

An alternative is to use word boundaries and full "words".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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