使用正则表达式提取匹配的文本

时间:2012-10-11 05:16:19

标签: c# regex

我必须从报纸文章中提取摘要。摘要是根据给定的关键字并根据下面提到的规则提取的。

  1. 摘要应为200个字符。

  2. 一旦关键字开始从文章中的那句话开始打印 出现在该句中并打印最多200个字符

  3. 如果匹配的句子出现在文章的结尾处,那么 摘要是不到200个字符,然后移动 从匹配的句子返回到先前的句子 最后打印出包含匹配句子的200个字符 最后。

  4. 我现在所做的一切都是......

    var regex = new Regex(keyword+@"(.{0,200})");
    
    foreach (Match match in regex.Matches(input))
    {
        var result = match.Groups[1].Value;
        Console.WriteLine(result);
    
        // work with the result
    }
    

    上面的代码成功到达了第一个匹配的句子,但是开始打印 AFTER 关键字最多200个字符,而不是开始匹配句子。

    如果在打印200个字符之前达到文章结尾,也没有回溯。

    请指导我如何继续。即使有人不知道完整的解决方案,请在问题的子部分帮助我。

3 个答案:

答案 0 :(得分:1)

var nextIndex = input.IndexOf(keyword);

while (nextIndex != -1)
{
    var index = nextIndex;
    // To start the 200chars result from right after the keyword, do instead:
    // var index = nextIndex + keyword.Length;

    // If you want to stop after you reached the end of the text once:
    // var end = false;

    if (index + 200 >= input.Length)
    {
        index = input.Length - 200;

        // If you want to stop after you reached the end of the text once:
        // var end = true;
    }

    var result = index < 0 ? input : input.Substring(index, 200);

    Console.WriteLine(result);

    // If you want to stop after you reached the end of the text once:
    // if (end) { break; }

    nextIndex = input.IndexOf(keyword, nextIndex + 1);
}

如果您希望搜索不区分大小写,只需在StringComparison.OrdinalIgnoreCase s中添加IndexOf作为另一个参数。

答案 1 :(得分:0)

请改用

var regex = new Regex( @"(" + keyword+ @".{0,200})");

这将确保包含关键字。否则你也可以使用这个

var result = match.Value;

此外,您已指定{0,200},因此它将匹配任何大小介于0到200之间的实例,因此它将匹配任意数量的字符,直到达到文章结尾。让我确切地知道你在这方面想要达到的目标。

如果希望表达式从句子的开头返回结果,请尝试执行此操作

var regex = new Regex( @"\.(.+?" + keyword+ @".*)");

但是在这种情况下,您必须手动删除多余的字符,因为这个正则表达式往往会获取您预期的更多字符。它将从包含关键字的句子的开头直到段落结尾处获取字符。

答案 2 :(得分:0)

正在使用正则表达式吗?如果不是,那么这是一个粗略的选择:

var index = input.IndexOf(keyword) + keyword.Length;
var remaining = input.Length - index;
index = remaining >= 200 ? index : index -= 200 - remaining;

Console.WriteLine(input.Substring(index, 200));