如果术语被搜索文本中的换行符破坏,如何使用RegEx查找术语

说我正在寻找“申请人”,并且事情发生在我之前,我收到一个这样的文本文件:

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

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

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

在搜索词中的每个字符之间插入[\t\r\n]* (匹配定义集中的零个或多个字符)。 然后,将文本的一部分从0索引分割到match.Index并使用正则表达式匹配换行符( @"\r?\n|\r" ),然后你去:

 var text = "Morelines\n\nWe have considered the applica\t\r\nnt'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(@"[\t\r\n]*", 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[\t\r\n]*p[\t\r\n]*p[\t\r\n]*l[\t\r\n]*i[\t\r\n]*c[\t\r\n]*a[\t\r\n]*n[\t\r\n]*t ---------- Match: applica nt at 34 ---------- Line No: 3 

将换行符替换为“”。

快速而肮脏的方式:

 applica\n?nt 

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