The regular expression is a domain specific language for the manipulation of text. Any programmer doing text processing of any nature would do well to acquaint themselves with this powerful language, that has implementations in all major languages.
In this series of articles I aim to point out some uses of regular expressions tha can make life much easier.
Take for example a situation where you have words with camel case.
For instance:
"ILikeFood", "iPhone" "FaceBook"
Suppose you wanted to print these words readably ... so "I Like Food, "i Phone", "Face Book"
A solution i've seen is to loop through each character and check its ASCII value and if it is above a certain threshold add a space an return a new string.
It may work but it's clumsy and unwieldy.
Another way to do it is to use a regular expression.
The strategy here is very simple.
This is easily accomplished with the following code
In C#:
1: using System.Text.RegularExpressions;
2: public Regex MyRegex = new Regex(
3: "([A-Z])",
4: RegexOptions.Multiline
5: | RegexOptions.CultureInvariant
6: | RegexOptions.Compiled
7: );
8:
9:
10: // This is the replacement string
11: public string MyRegexReplace =
12: " $1";
13:
14: //// Replace the matched text in the InputText using the replacement pattern
15: string result = MyRegex.Replace(InputText,MyRegexReplace);
In VB.NET
1: Imports System.Text.RegularExpressions
2:
3: Public Dim MyRegex As Regex = New Regex( _
4: "([A-Z])", _
5: RegexOptions.Multiline _
6: Or RegexOptions.CultureInvariant _
7: Or RegexOptions.Compiled _
8: )
10:
11: ' This is the replacement string
12: Public Dim MyRegexReplace As String = _
13: " $1"
14:
15:
16: '' Replace the matched text in the InputText using the replacement pattern
17: Dim result As String = MyRegex.Replace(InputText,MyRegexReplace)
Agreed, Regular expressions are pretty effective. but like everything effective it can be cryptic. while unix developers have had it for a while, it is slowly but in a better structured manner being utilized by windows developers.
the most common thing i know its for is, email validation, telephone number validation e.t.c. while learning curve of regular expressions can be steep - you need only to learn it once and utilize it in any language of choice. thus said it is a worthwhile investment
many resources are out there for your persusal....Rad maybe is should give a talk on this!!