如何在字符串中查找特定句子的所有出现?

时间:2012-08-31 18:16:18

标签: c# regex linq substring

假设我有一个这样的字符串:

string source = "Today is friday! I'm am having trouble programming this. Today is friday! Tomorrow is saturday. Today is friday!"

我想搜索这个字符串,抓住所有句子说“今天是星期五!”,并用我刚刚找到的句子创建一个新字符串。

上述字符串的预期结果是:

string output = "Today is friday!Today is friday!Today is friday!"

编辑:LINQ不是强制性的。

谢谢!

4 个答案:

答案 0 :(得分:6)

这是一种非LINQ方法:

string str = "Today is friday! I'm am having trouble programming this. Today is friday! Tomorrow is saturday. Today is friday!";

StringBuilder sb = new StringBuilder();
int index = 0;
do
{
    index = str.IndexOf("Today is friday!", index);
    if (index != -1)
    {
        sb.Append("Today is friday!");
        index++;
    }
} while (index != -1);

string repeats = sb.ToString();

答案 1 :(得分:4)

实际上没有必要找到比赛。由于您是根据搜索模式创建新字符串,因此只需搜索字符串的计数就足够了。如果您愿意,可以使用更快的子字符串计数算法替换正则表达式。

string source = "Today is friday! I'm am having trouble programming this. Today is friday! Tomorrow is saturday. Today is friday!";
string searchPattern = "Today is friday!";
int count = Regex.Matches(source, searchPattern).Count;
string result = string.Concat(Enumerable.Repeat(searchPattern, count));

答案 2 :(得分:4)

正则表达式

查找

.*?(Today is friday).*?(?=\1|$)

替换:

$1

说明

.*?                 # match everything before an occurrence of the sentence
(Today is friday!)  # match the sentence
.*?                 # match everything after the sentence...
(?=\1|$)            # ...up to the next occurrence or end of the string

答案 3 :(得分:2)

好的,你需要做的第一件事就是把你的一个字符串变成很多。 String.Split()应该在这里工作,不需要正则表达式:

var sentences = inputString.Split('.','!');

一旦你有了单独的句子,你只需要寻找符合标准的句子:

var todayIsFridaySentences = sentences.Where(s=>s.Contains("Today is friday"));

......然后最后把它们放回原处;如果你绝对必须使用Linq:

var ouputString = todayIsFridaySentences
                     .Aggregate(new StringBuilder(), (s,b) => b.Append(s))
                     .ToString();