搜索文件中的字符,希望每次從每行的開始進行匹配。
所以在表達式開頭加了\n
結果發現怎么都匹配不了。
string regEx = @"\n\d*\s*!\s*TESTNAME”
最后,偶然發現,原來必須是\n,而不是\\n,
不能再字符串的開頭添加@字符。
去掉@后,后面的轉義字符依次添加\進行\的轉義。
匹配正常了。
string regEx = "\n\\d*\\s*!\\s*TESTNAME“
搜索文本的代碼體如下:
string fileContent = File.ReadAllText(path); Match m; int line = 0; try { m = Regex.Match(fileContent, regEx, RegexOptions.IgnoreCase); } catch (Exception ex) { return 0; } if (m.Captures.Count > 0) { line = fileContent.Substring(0, m.Captures[0].Index+1).Count(f => f == '\n'); return line; } else { return 0; }
小小的紀念一下在這上面浪費掉的時間。。。
