Display next set of words in a string
-
10-06-2021 - |
Pergunta
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?
Solução
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;
Outras dicas
If you want to match multiple string
s,
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.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow