如何获取正则表达式匹配项的精确行位置?
获取正则匹配项的精确行位置解决方案
我来帮你搞定这个问题!你想要获取正则匹配结果所在的精确行号,核心就是补全你没写完的LineFromPos方法。下面给你完整的实现思路和代码:
核心逻辑
行号的计算其实很简单:匹配项的起始索引位置之前,有多少个换行符,行号就是这个数量加1(因为第一行没有前置换行符,从1开始计数)。需要注意兼容不同的换行格式(Windows的\r\n和Unix/Linux的\n)。
完整代码实现
using System; using System.Text.RegularExpressions; class Program { static void Main() { string text = @"What is the value of pn in 1 ;/ This is a test 12./ lop"; string pattern = @"\d\s?[.,;:]\s?/"; foreach (Match m in Regex.Matches(text, pattern)) { int lineNumber = LineFromPos(text, m.Index); Console.WriteLine($"行号: {lineNumber}, 起始索引: {m.Index}"); } Console.Read(); } // 补全的行号计算方法 public static int LineFromPos(string text, int index) { if (index < 0 || index >= text.Length) throw new ArgumentOutOfRangeException(nameof(index)); // 统计从文本开头到index位置前的换行符数量 // 兼容\r\n和\n两种换行格式 int lineCount = 1; int pos = 0; while ((pos = text.IndexOfAny(new char[] {'\r', '\n'}, pos)) != -1 && pos < index) { lineCount++; // 如果是\r\n,跳过第二个字符避免重复计数 if (text[pos] == '\r' && pos + 1 < text.Length && text[pos + 1] == '\n') { pos++; } pos++; } return lineCount; } }
代码说明
LineFromPos方法会遍历文本从开头到匹配索引的位置,统计所有换行符的数量,每遇到一个换行就把行号加1- 同时处理了
\r\n(Windows换行)和\n(Unix换行)两种情况,避免重复计数 - 加入了参数合法性检查,防止传入无效索引
测试结果
你的示例文本没有换行,所以两个匹配项的行号都是1,运行后输出:
行号: 1, 起始索引: 31 行号: 1, 起始索引: 52
如果你的文本有多行,比如:
What is the value of pn in 1 ;/ This is a test 12./ lop
那么第一个匹配项行号是1,第二个是2,完全符合预期。
内容的提问来源于stack exchange,提问作者Ab Laxman
相关产品推荐
相关产品推荐

