Thursday, December 13, 2012

Add Space Before Capital Letter

In one of my recent project my requirement was to add a space before a capital letter like, if our word is "HiAmbika" then we have to convert it to "Hi Ambika".

Example: 
Input String: "RajaRamMohamRoy"
Output       :  "Raja Ram Mohan Roy"

I just used regular expression in ColdFusion to achieve this as follows.

<cfscript>
request.inputString = "RajaRamMohamRoy";
request.outputString = rEReplace(request.inputString, "([a-z])([A-Z])", "\1 \2", "ALL");
writeOutput("<b>Input String:</b>" & request.inputString & "<br/>");
writeOutput("<b>Output String:</b>" & request.outputString & "<br/>");
/*
Here regular expression we have used is "([a-z])([A-Z])"
then replacing that matching pattern with "\1 \2". Which means we are searching for a string
which lower case and upper case letter consecutively. Like aA or bC.
Then we are using regular expresson back refrencing trick to add a space between these two matching pattern.
( #Match and Capture pattern 1
[a-z] #must be a lower case alphabet
) #End of pattern 1
( #Match and Capture pattern 2
[A-Z] #must be a upper case alphabet
) # End of pattern 2
*/
</cfscript>
view raw gistfile1.cfm hosted with ❤ by GitHub

We can also do other advance string matching functionality with back referencing. We will see that latter.


2 comments:

Followers