1

Is it possible to convert an all-uppercase string into a string where only the first letter of each word is in upper case using regular expressions?

THIS IS A SAMPLE STRING ---> This Is A Sample String

At first I thought this would be an easy task, but now I don't even know how to start or even if it is possible.

Daniel Rikowski
  • 71,375
  • 57
  • 251
  • 329
  • No particular language. I need this for a custom application where the only way to transform a text is through regular expressions. (with Perl extensions to be precise) – Daniel Rikowski Sep 26 '10 at 20:34
  • Regexps are symbol acceptors, they are only used to match strings. You really need to specify what kind of "replace" you are referring to. A replace operation has a "match" step (i.e. the regexp+flags) and a substitution step (i.e. the replacement expression). Depending on the implementation, the replacement expression can contain group references (e.g. $1) and other type of operations (e.g. "retain-case", "to-uppercase") – gawi Sep 26 '10 at 21:04

2 Answers2

3

In Perl:

$string =~ s/([\w']+)/\u\L$1/g;

(taken from the Perl FAQ)

gawi
  • 13,940
  • 7
  • 42
  • 78
1

No, in most languages you can't use regular expressions to do that. An exception to this is Perl which has a particularly powerful "regular" expression syntax.

You will probably find that your language has a library function that can do it. Look for something like s.titlecase().

Related:

Community
  • 1
  • 1
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452