显示字符串中的下一组单词 [英] Display the next set of words in a string

查看:83
本文介绍了显示字符串中的下一组单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  int  numberOfWords =  50 ;
字符串 regexMatch = 字符串 .Format( @"  ^(\ w + \ b.*?){{" + numberOfWords +  }}");
字符串 firstWords = Regex.Match(result,regexMatch).Value; 



此代码显示字符串中的前50个字.现在,我想显示下一个50个单词(第51个到第100个单词).我该怎么做呢?单词作为记录).
我能想到的最好的解决方案是进行上述匹配,然后使用Regex.Replace将其删除并再次进行.

讨厌:但这不是正则表达式的目的!


如果您的要求是找到each set of 50 words,那么我认为Regex 类的Matches 方法可以是用法如下所示:

 字符串 result = "  int  numberOfWords =  2 ;
字符串 regexMatch =  @"  + numberOfWords +  }";
MatchCollection foundWords = Regex.Matches(结果,regexMatch);
 foreach (在 in 中找到匹配词)
    Console.WriteLine(match.Value);

// 输出

// 一二
// 三分之四
// 五个六个
// 七八
//  9  


在上面的示例中,我采用了numberOfWords = 2来说明这一点.可以替换为50.


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?

解决方案

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!


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

//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.


这篇关于显示字符串中的下一组单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆