Count Occurences of a Token in a StringHaving fun with Regex's | | 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
}
| You can of course pass in 'text' and '_pattern' and use this in a more generic mode. Like I said before though, this is as simple as it gets with Regex's. My next article, I'm going to do the same thing getting a little more fancy, using CaptureCollections and some other cool features.
The long and short of it is that text parsing without Regex's isn't all that fun. As a matter of fact, they can make things that are otherwisek brutal, quite simple. I just wished I'd have learned them a few years back! |