With the onset of .NET, I quickly began to feel my age. Granted, at 32 I shouldn't be whining about age but here I am. You see, I took my Computer Science classes a few years ago and missed out on a lot. While teaching myself new things has always been something I do pretty well, not everything sticks. And these days, I really wish I would have spent my time learning the in's and out's of regex's instead of learning to prove my table designs with both algebra and calculas.... but I digress.
I'm going to come up with a very very simple example of something cool you can do with a regex. Let's say you have a sentence and you want to know how many Commas are in it. Or you have a long string and want to count the instances of a word in it. Or how many words start with a capital letter or any such thing. In comes the Regex and the beloved Match collection. There are multiple ways to accomplish this, but I'm going to show one quick and easy one:
First, make sure you include this line:
| using System.Text.RegularExpressions; Then, add in the following: public int CountOccurrences() { string text = "One, two, three, four, five, six"; string _pattern = @"\,"; Regex r = new Regex(_pattern, RegexOptions.IgnoreCase); // Match the regular expression pattern against a text string. MatchCollection ma = r.Matches(text); return ma.Count; //returns five } |