Frage

I have the following code:

 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?

War es hilfreich?

Lösung

You can use the same regex but starting after first 5o words. As you have first 50 words in firstWords so we have to start after these fifty words. So we will take substring of the result after fifty words which we have in firstWords. firstWords.Length will become new starting point for regex for second 5o words.

 string secondWords = Regex.Match(result.Substring(firstWords.Length).Trim(), regexMatch).Value;

Andere Tipps

If you want to match multiple strings,

Code Like this :

List<string> Words = new List<string>();
for(int i = 0; (result.Length - (i * numberOfWords)) < numberOfWords; i++)
{
    Words.Add(Regex.Match(result.Substring(i * numberOfWords).Trim(), regexMatch).Value)
}

You get a List of the 50 words present in the string! However if at the end of the string there is less than 50 words it will not add the word those to the Words List.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top