【发布时间】:2016-09-04 09:32:42
【问题描述】:
我正在尝试寻找验证输入文档的最佳解决方案。我需要检查文档的每一行。基本上每一行都可以存在无效字符或字符。搜索(验证)的结果是:'get me the index with invalid char and index of the line in this line'.
我知道如何以标准方式(打开文件 -> 读取所有行 -> 逐一检查字符),但这种方法不是最佳优化方式。取而代之的是,最好的解决方案是使用“MatchCollection”(在我看来)。
但是如何在 C# 中正确地做到这一点呢?
链接:
示例:
“在此处输入一些文字,\n 是该文字的另一条文字。”
在第一行 [0] 在 [6] 索引上发现无效字符,在行 [1] 在 [0, 12, 21] 索引上发现无效字符。
using System;
using System.Text.RegularExpressions;
namespace RegularExpresion
{
class Program
{
private static Regex regex = null;
static void Main(string[] args)
{
string input_text = "Some Înput text here, Îs another lÎne of thÎs text.";
string line_pattern = "\n";
string invalid_character = "Î";
regex = new Regex(line_pattern);
/// Check is multiple or single line document
if (IsMultipleLine(input_text))
{
/// ---> How to do this correctly for each line ? <---
}
else
{
Console.WriteLine("Is a single line file");
regex = new Regex(invalid_character);
MatchCollection mc = regex.Matches(input_text);
Console.WriteLine($"How many matches: {mc.Count}");
foreach (Match match in mc)
Console.WriteLine($"Index: {match.Index}");
}
Console.ReadKey();
}
public static bool IsMultipleLine(string input) => regex.IsMatch(input);
}
}
输出:
- 是单行文件
- 匹配数:4
- 索引:5
- 索引:22
- 索引:34
- 索引:43
【问题讨论】:
-
什么是“无效字符”?标准方式可能更快,发布一些代码。
-
我怀疑你想匹配任何不是 ascii 的字母。试试
Regex.Matches(s, @"[\p{L}-[a-zA-Z]]")。但是,这不会包含任何行索引信息。 -
就像在代码中一样,我找不到使用 MatchCollection 的多行解决方案。
标签: c# regex validation