假设我正在搜索“申请人”,正如我之前发生过的事情一样,我收到一个如下的文本文件:
We have considered the applica
nt's experience and qualification,
and wish to grant him an interview.
现在我仍然希望我的正则表达式返回整个单词“applicant”的索引 23 处的匹配,并且我想告诉用户部分匹配从线上开始m和列n。我怎样才能实现这个目标?
我想到的一个相当乏味的解决方案是在每次匹配之前插入一个特殊的标记字符,每次都会增加剩余匹配的索引。然后逐行重复搜索,并查找后跟搜索词的第一个字符的标记。
Insert [\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));
}
See the 在线 C# 演示 http://ideone.com/QnTO9C
Output:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)