Monday, December 3, 2012

Regular expression - Replace exact word matched string

Regular expression are really helpful .There is no second thought on it. But as the fundamentals of regex is little difficult to digest for non-computer science graduates and most of the computer programmers are from non computer science background, it is very difficult to see regex in the production code. I don't know about the percentage of non computer graduates in programming in other countries, but in India its high. But there are exceptions as well, some of them spent time for learning these kind of things and applies in their programming life.

Anyway it is not the intention of this post to discuss about non computer science programmers using regex or not. This post will be listing out scenarios where a regular reducing a bulk amount of code

Find out exact word and replace

Lets consider the sentence "During blogging joymon's soul is filled with joy". We need to change the word 'joy' with 'happiness' .If we just use string.replace in .net it willl replace as "During blogging happinessmon's soul is filled with happiness".

         Dim  orgSentence = "During blogging joymon's soul is filled with joy" 
         Dim  replacedSentence = orgSentence.Replace("joy" , "happiness" )


Out put will be "During blogging happinessmon's soul is filled with happiness"

It did the task well but we didn't want 'joymon' to be replaced with "happinessmon".Unfortunately string.replace don't have flexibility to say replace only exact word matches. We can write a big function to achieve the same.But should we really need that as there are regular expression? Certainly not.We can achieve the same easily using regex.The code is as follows.

Dim  orgSentence = "During blogging joymon's soul is filled with joy" 
Dim  pattern As  String  = "\b"  + "joy"  + "\b" 
Dim  replaceWith = "happiness" 
Dim  reg As  Regex  = New  Regex (pattern)
Dim  replacedSentence As  String  = reg.Replace(orgSentence, replaceWith, 1, 0)
 

'\b' refers to word boundary.For more details on reg expressions visit the below links
http://msdn.microsoft.com/en-us/library/az24scfc.aspx#atomic_zerowidth_assertions
http://www.regular-expressions.info/wordboundaries.html

No comments: