4

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

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

4 回答 4

7

这是一种非 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();
于 2012-08-31T18:41:17.297 回答
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));
于 2012-08-31T18:34:21.813 回答
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
于 2012-08-31T21:02:45.003 回答
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();
于 2012-08-31T18:23:01.207 回答