Title Case for a sentence ending with parentheses

Viewed 146

I would like to title case every sentence ending with parentheses containing uppercase letters only NB: do not title case certain words such as "for, and, the" for instance.

So the original sentence is:

foundation for economic education (FEE)

And it should be like that:

Foundation for Economic Education (FEE)

Any help is much appreciated!

Here is my "faulty" code, it capitalizes everything before the parenthesis...

(^[\p{L}\W]+)([(][\p{Lu}]{3,}[)]$)

\U\1\2
1 Answers

The regex that matches a string with no uppercase letters ending with (...) substring is, for example:

/^(\P{Lu}*)(?=\([^()]*\)$)/

See the regex demo. There are other ways, but this way makes it more convenient to build the replacement part, RHS, in Perl later.

Pattern details:

  • ^ - start of string
  • (\P{Lu}*) - Group 1: any zero or more chars other than uppercase letters
  • (?=\([^()]*\)$) - a positive lookahead that requires (, then any zero or more chars other than ( and ) and then a ) at the end of the string ($).

Then you may use the Lingua::EN::Titlecase like this:

#!/usr/bin/perl
use feature 'say';
use strict;
use warnings;
use Lingua::EN::Titlecase;

my $tc = Lingua::EN::Titlecase->new();
my $str = "foundation for economic education (FEE)";
say $str =~ s{^(\P{Lu}*)(?=\([^()]*\)$)}{ $tc->title($1) }re;

Output: Foundation for Economic Education (FEE).

Related