我正在研究一个代码,该代码可以扫描多个.docx文件中的某个关键字,然后给出整个句子,直到换行。
此功能很好用,我得到包含关键字的每个句子,直到出现换行符为止。
我的问题:
当我不希望文本直到第一个换行符,但是直到第二个换行符为止,我的RegEx看起来如何?也许使用正确的量词?我没有让它工作。
我的模式:".*" + "keyword" + ".*"
Main.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using Xceed.Words.NET;
public class Class1
{
static void Main(string[] args)
{
String searchParam = @".*" + "thiskeyword" + ".*";
List<String> docs = new List<String>();
docs.Add(@"C:\Users\itsmemario\Desktop\project\test.docx");
for (int i = 0; i < docs.Count; i++)
{
Suche s1 = new Suche(docs[i], searchParam);
s1.SearchEngine(docs[i], searchParam);
}
}
}
zhi.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using Xceed.Words.NET;
public class Suche
{
String path;
String stringToSearchFor;
List<String> searchResult = new List<String>();
public Suche(String path, String stringToSearchFor)
{
this.path = path;
this.stringToSearchFor = stringToSearchFor;
}
public void SearchEngine(String path, String stringToSearchFor)
{
using (var document = DocX.Load(path))
{
searchResult = document.FindUniqueByPattern(stringToSearchFor, RegexOptions.IgnoreCase);
if (searchResult.Count != 0)
{
WriteList(searchResult);
}
else
{
Console.WriteLine("Text does not contain keyword!");
}
}
}
public void WriteList(List<String> list)
{
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i]);
Console.WriteLine("\n");
}
}
}
预期输出类似于
"*LINEBREAK* Theres nothing nicer than a working filter for keywords. *LINEBREAK*"
答案 0 :(得分:1)
您无法使用document.FindUniqueByPattern
DocX方法来跨行匹配,因为它仅在单个段落中搜索。参见bind,即foreach( Paragraph p in Paragraphs )
。
您可以获取document.Text
属性,或将所有段落文本合并为一个并在整个文本中进行搜索。删除searchResult = document.FindUniqueByPattern(stringToSearchFor, RegexOptions.IgnoreCase);
行并使用
var docString = string.Join("\n", document.Paragraphs.Select(p => p.text));
// var docString = string.Join("\n", document.Paragraphs.SelectMany(p => p.MagicText.Select(x => x.text)));
searchResult = Regex.Matches(docString, $@".*{Regex.Escape(stringToSearchFor)}.*\n.*", RegexOptions.IgnoreCase)
.Cast<Match>()
.Select(x => x.Value)
.ToList();