c# - c# RegEx 匹配在哪一行。林克?
问题描述
这个应该很简单,但它难倒我。
我有一个可以匹配的正则表达式。如果是这样,我想知道它在哪条线上。有没有一种简单的方法可以用 Linq 做到这一点,而不用遍历每一行来计算字符?
Regex rx = new Regex(myRegEx, RegexOptions.Compiled | RegexOptions.IgnoreCase);
string[] docLines = File.ReadAllLines(myDocPath);
// Find matches
MatchCollection matches = rx.Matches(string.Join(Environment.NewLine, docLines));
if(matches.Count > 0)
{
long loc = matches[0].Index;
//Find the Line
}
解决方案
您可以逐行匹配:
Regex rx = new Regex(myRegEx, RegexOptions.Compiled | RegexOptions.IgnoreCase);
string[] docLines = File.ReadAllLines(myDocPath);
// Find matches
for(int x = 0; x < docLines.Length; x++){
string line = docLines[x];
if(rx.IsMatch(line))
Console.Write($"Match on line {x}");
}
推荐阅读
- tcl - 在 TCL 语言中理解正则表达式有困难
- javascript - 使用graphql查询检查反应js中的空对象
- php - 如何每天自动运行php文件
- javascript - 未捕获(承诺中)错误:使用 Laravel 请求失败,状态码 404
- javascript - 在 JavaScript 中根据 id 属性合并两个对象
- php - 我有将验证码图像从 captcha.php 设置到 register.php 中的 src 的 ajax 问题
- android - 在 backpress 上的两个片段之间导航
- c++17 - 局部变量 C++ 的随机初始化
- docker - 我在我的 docker 文件中添加了 git clone。镜像构建成功
- php - google adwords API 授权请求