我試圖找到驗證輸入文檔的最佳解決方案。我需要檢查文檔的每一行。基本上每行可以存在無效的字符或字符。搜索(驗證)的結果是:'讓我找到具有無效字符的行的索引以及此行中每個無效字符的索引'。正則表達式對文檔進行過濾
我知道怎麼用標準的方式(打開文件 - >讀取所有行 - >逐個檢查字符),但是這種方法並不是最佳的優化方式。相反,最好的解決方案是使用「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使用的多行解決方案。 – Nerus