首页 > 解决方案 > Perl, Change the Case of Letter at { character

问题描述

I am a perl newb, and just need to get something done quick and dirty. I have lines of text (from .bib files) such as

Title = {{the Particle Swarm - Explosion, Stability, and Convergence in a Multidimensional Complex Space}},

How can I write a regex such that the first letter after the second { becomes capitalised.

Thanks

标签: regexperl

解决方案


One way, for the question as asked

$string =~ s/{{\K(\w)/uc($1)/ge;

whereby /e makes it evaluate the replacement side as code. The \K makes it drop all previous matches so {{ aren't "consumed" (and thus need not be retyped in the replacement side).

If you wish to allow for possible spaces:  $string =~ s/{{\s*\K(\w)/uc($1)/ge;, and as far as I know bibtex why not allow for spaces between curlies as well, so {\s*{.

If simple capitalization is all you need then \U$1 in the replacement side sufficies and there is no need for /e modifier with it, per comment by Grinnz. The \U is a generic quote-like operator, which can thus also be used in regex; see under Escape sequences in perlre, and in perlretut.

I recommend a good read through the tutorial perlretut. That will go a long way.

However, I must also ask: Are you certain that you may indeed just unleash that on your whole file? Will it catch all cases you need? Will it not clip something else you didn't mean to?


推荐阅读