Click here to Skip to main content
15,886,067 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
int numberOfWords = 50;
string regexMatch = string.Format(@"^(\w+\b.*?){{" + numberOfWords + "}}");
string firstWords = Regex.Match(result, regexMatch).Value;


This code displays the first 50 words in a string. Now I want to display next 50 words (51st word to 100th word). How do I do it?
Posted
Comments
VJ Reddy 28-Jun-12 9:53am    
Thank you for viewing and accepting the solution :)

There is no way in straight regexes to do that: it is a text processing system, not a record based system (albeit with single words as a record).
The best solution I can come up with is to do the match as above, then use Regex.Replace to remove them and do it again.

Nasty: but it's not what regexes were designed for!
 
Share this answer
 
If your requirement is to find each set of 50 words, then I think the Matches method of Regex class can be used as shown below:
C#
string result = "one two three four five six seven eight nine";
int numberOfWords = 2;
string regexMatch = @"(\w+\s*){" + numberOfWords + @"}";
MatchCollection foundWords= Regex.Matches(result, regexMatch);
foreach (Match  match in foundWords)
    Console.WriteLine (match.Value);

//Output

//one two
//three four
//five six
//seven eight
//nine

In the above example I have taken numberOfWords = 2 to illustrate the point. It can be replaced with 50.
 
Share this answer
 
Comments
Espen Harlinn 23-May-12 5:27am    
5'ed!
VJ Reddy 23-May-12 6:19am    
Thank you, Espen :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900