Parse Camel Case into Words

I was working on a small project that had a list of camel case strings that I wanted to display to users. Displaying values as camel case feels dirty, though, so I wanted to pretty it up by parsing the strings into words. Sounds like a job for regular expressions!

After a few tries, this is what I settled on:

var x = Regex.Replace(value, @"([A-Z][^A-Z])", " $1");
x = Regex.Replace(x, "([a-z])([A-Z])", "$1 $2");
x = x.Trim();

Here are my test cases and the results:

Input:
  HelloWorld
  SuperMB
  SMBros
  OneTWOThree

Results:
  Hello World
  Super MB
  SM Bros
  One TWO Three

Ahh, just what I was hoping for. Thanks again, regular expressions!

Advertisement

Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: