Click here to Skip to main content
Rate this: bad
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 at 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 at 23-May-12 5:27am
VJ Reddy at 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)

Advertise | Privacy | Mobile
Web01 | 2.8.150326.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