我有一个大文本。我需要在文本中找到任何单词,然后将包含该单词的短语复制到变量中。我怎样才能用 C# 做到这一点?也许我可以使用一些正则表达式?
使用正则表达式[^.!?;]*(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());
Run Code Online (Sandbox Code Playgroud)
此代码使用正则表达式查找所有包含“professional”的句子,并输出它们,修剪所有空格。
输出:Stack Overflow is a question and answer site for professional and enthusiast programmers.