从文本中提取包含单词的句子

时间:2014-12-21 18:31:16

标签: c# regex

我有一个大文字。我需要在文本中找到任何单词然后复制到包含单词的短语变量。我怎么能用C#做到这一点?也许我可以使用一些正则表达式?

1 个答案:

答案 0 :(得分:3)

使用正则表达式[^.!?;]*(search)[^.?!;]*[.?!;],其中"搜索"是你的查询。

string query = "professional";
var regex = new Regex(string.Format("[^.!?;]*({0})[^.?!;]*[.?!;]", query));
string text =
    @"Stack Overflow is a question and answer site for professional and enthusiast programmers. 
    It's built and run by you as part of the Stack Exchange network of Q&A sites.
    With your help, we're working together to build a library of detailed answers to 
    every question about programming.";

var results = regex.Matches(text);

for (int i = 0; i < results.Count; i++)
    Console.WriteLine(results[i].Value.Trim());

此代码使用正则表达式查找包含&#34; professional&#34;的所有句子,并输出它们,修剪任何空格。

输出:Stack Overflow is a question and answer site for professional and enthusiast programmers.