Follow in Twitter & Facebook

Like in Facebook

Powered By Blogger Widgets

Free Download

FREE Tools

Tuesday, May 22, 2012

Extract first N words from a string with C#.Net

Here we will describe how to get the first n words of a String using C#.Net. Also you can check an article on String and StringBuilder in C#.Net.

You can extract first N words from a string by converting an array. But here we will discuss how we can do using RegularExpressions like below:

string strWholeString = "String1 String2 String3 String4 String5 String6 String7 String8"
string extractedString = Regex.Match(strWholeString, @"^(\w+\b.*?){5}").ToString();

Here 5 is the number words you want to retrive.
The above regular expression will return "String1 String2 String3 String4 String5";

But we will get exception if the Number of words we are retrieve is less than the total words.

So it is better to retrieve how many words the string contains like below:
We can retrieve the count by using MatchCollection class like below:

MatchCollection collection = Regex.Matches(strWholeString, @"[\S]+");
int count = collection.Count;
string firstWords = Regex.Match(strWholeString, @"^(\w+\b.*?){" + count + "}").ToString();

All the classes with using System.Text.RegularExpressions; Namespace.

0 on: "Extract first N words from a string with C#.Net"