Click here to Skip to main content
11,927,324 members (50,570 online)
Rate this:
Please Sign up or sign in to vote.
See more: C# string
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 22-May-12 21:14pm
VJ Reddy 28-Jun-12 9:53am
Thank you for viewing and accepting the solution :)
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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!
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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:
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);

//one two
//three four
//five six
//seven eight
In the above example I have taken numberOfWords = 2 to illustrate the point. It can be replaced with 50.
Espen Harlinn 23-May-12 5:27am
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web04 | 2.8.151126.1 | Last Updated 23 May 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100