如何使用RegEx找到一个术语,如果该术语在搜索文本中被新行打破



假设我正在搜索"申请人",就像以前发生在我身上的事情一样,我收到一个这样的文本文件:

We have considered the applica
nt's experience and qualification, 
and wish to grant him an interview.

现在我仍然希望我的RegEx在索引23处返回整个单词"申请人"的匹配,并且我想告诉用户部分匹配开始于行m和列n。我怎样才能做到这一点呢?

我想到的一个相当乏味的解决方案是在每个匹配之前插入一个特殊的标记字符,每次增加剩余匹配的索引。然后逐行重复搜索,查找与搜索词的第一个字符后面跟着的标记。

在搜索词的每个字符之间插入[trn]*(匹配定义集合中的零个或多个字符)。然后,使用匹配换行符(@"r?n|r")的正则表达式将从0索引开始的部分文本拆分为match.Index,然后就可以了:

var text = "MorelinesnnWe have considered the applicatrnnt's experience and qualification, nand wish to grant him an interview.";
Console.WriteLine(string.Format("Our text:n{0}n---------", text));
var search = "applicant";
var pattern = string.Join(@"[trn]*", search.ToCharArray());
Console.WriteLine(string.Format("Our pattern: {0}n----------", pattern));
var result = Regex.Match(text, pattern);
if (result.Success) {
    Console.WriteLine(string.Format("Match: {0} at {1}n----------", result.Value, result.Index));
    var lineNo = Regex.Split(text.Substring(0, result.Index), @"r?n|r").GetLength(0);
    Console.WriteLine(string.Format("Line No: {0}", lineNo));
}

查看在线c#演示

输出:

Our text:
Morelines
We have considered the applica  
nt's experience and qualification, 
and wish to grant him an interview.
---------
Our pattern: a[trn]*p[trn]*p[trn]*l[trn]*i[trn]*c[trn]*a[trn]*n[trn]*t
----------
Match: applica  
nt at 34
----------
Line No: 3

将换行符替换为"。

快捷方式:

applican?nt

如果你不知道换行符应该出现在哪里,那么在每个字符之间添加它。

最新更新