Not feelin’ the regex love

thehemorrhoid Sometimes I come to a regular expression in code that someone else wrote (and they probably just ripped it off from stackoverflow or some such place and never bothered to understand exactly how it worked), and there are no comments explaining what this regex is intended to do.  Infuriating.  It not only counts on the developer down the road to know regular expressions well enough to figure out what it is supposed to be doing, but it also requires a bit of cross-temporal mind-meld to figure out what the problem was that the original developer was trying to solve.  Inevitably there will be some case that comes up and the particular regex they selected doesn’t handle it well.  It needs to be tweaked, so now you have to go about understanding the whole thing and the original developer left you no clues.


Regex use versus abuse

CamelCase to Human Readable String

What to do?

Your decision about whether to figure it all out or just write some code that does the same thing may well depend upon how near your deadline is looming.

Faced with such a situation recently, with absolutely no time at all to handle this stupid little cosmetic bug, I opted for the just-write-the-damn-code option.

CamelCase to English in Actionscript

I just had to turn a camelCase string (I like to write camelCase in camelCase), into something more beautiful that you could display to a user.  The existing regex worked pretty well, except it fell down when an acronym was involved – too many capital letters in a row.  So you had a string LOLCatsAreFunny, and it ended up LOLCats Are Funny.  I needed that space between LOL and Cats.

Found a good place to start by 1.21 Gigawats at stackoverflow.  That solution didn’t have the tweak I needed, so here is the modified solution.  The tweak is in pink.

public static function prettifyCamelCase(value:String=""):String 
var output:String = ""; 
var len:int = value.length; 
var nextChar:String = ""; 

for (var i:int; i < len; i++) 
    char = value.charAt(i); 
    if (i < len - 1) 
        nextChar = value.charAt(i + 1); 

    if (i==0)
        output += char.toUpperCase(); 
    else if (char !== char.toLowerCase() && char === char.toUpperCase()
        && nextChar === nextChar.toLowerCase() 
        && nextChar !== nextChar.toUpperCase()) 
        output += " " + char;
    else if (char == "-" || char == "_")
        output += " ";
        output += char; 
return output; 



Leave a Reply

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

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

Twitter picture

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

Facebook photo

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

Connecting to %s