【问题标题】:Document filtering by regex通过正则表达式过滤文档
【发布时间】:2016-09-04 09:32:42
【问题描述】:

我正在尝试寻找验证输入文档的最佳解决方案。我需要检查文档的每一行。基本上每一行都可以存在无效字符或字符。搜索(验证)的结果是:'get me the index with invalid char and index of the line in this line'.

我知道如何以标准方式(打开文件 -> 读取所有行 -> 逐一检查字符),但这种方法不是最佳优化方式。取而代之的是,最好的解决方案是使用“MatchCollection”(在我看来)。

但是如何在 C# 中正确地做到这一点呢?

链接:

http://www.dotnetperls.com/regex-matches

示例:

“在此处输入一些文字,\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


【解决方案1】:

链接: http://www.dotnetperls.com/regexoptions-multiline

解决方案

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))
            {
                Console.WriteLine("Is a multiple line file");

                MatchCollection matches = Regex.Matches(input_text, "^(.+)$", RegexOptions.Multiline);

                int line = 0;

                foreach (Match match in matches)
                {
                    foreach (Capture capture in match.Captures)
                    {
                        line++;

                        Console.WriteLine($"Line: {line}");

                        RegexpLine(capture.Value, invalid_character);
                    }
                }
            }
            else
            {
                Console.WriteLine("Is a single line file");

                RegexpLine(input_text, invalid_character);
            }

            Pause();
        }

        public static bool IsMultipleLine(string input) => regex.IsMatch(input);

        public static void RegexpLine(string line, string characters)
        {
            regex = new Regex(characters);

            MatchCollection mc = regex.Matches(line);

            Console.WriteLine($"How many matches: {mc.Count}");

            foreach (Match match in mc)
                Console.WriteLine($"Index: {match.Index}");
        }

        public static ConsoleKeyInfo Pause(string message = "please press ANY key to continue...")
        {
            Console.WriteLine(message);

            return Console.ReadKey();
        }
    }
}

谢谢各位帮忙,如果有人比我聪明,基本上会很好,检查这段代码的性能。

问候, 尼鲁斯。

【讨论】:

    【解决方案2】:

    我的方法是将字符串拆分为字符串数组,每个字符串包含一行。如果数组的长度仅为 1,则意味着您只有 1 行。然后从那里你使用正则表达式匹配每一行来找到你正在寻找的无效字符。

    string input_text = "Some Înput text here,\nÎs another lÎne of thÎs text.";
    string line_pattern = "\n";
    
    // split the string into string arrays
    string[] input_texts = input_text.Split(new string[] { line_pattern }, StringSplitOptions.RemoveEmptyEntries);
    
    string invalid_character = "Î";
    
    if (input_texts != null && input_texts.Length > 0)
    {
        if (input_texts.Length == 1)
        {
            Console.WriteLine("Is a single line file");
        }
    
        // loop every line
        foreach (string oneline in input_texts)
        {
            Regex regex = new Regex(invalid_character);
    
            MatchCollection mc = regex.Matches(oneline);
    
            Console.WriteLine("How many matches: {0}", mc.Count);
    
            foreach (Match match in mc)
            {
                Console.WriteLine("Index: {0}", match.Index);
            }
        }
    }
    

    --- 编辑 ---

    需要考虑的事项:

    • 如果您从文件中获取输入,我建议您逐行阅读,而不是全文阅读。
    • 通常,当您搜索无效字符时,您不会指定它。相反,你寻找一种模式。例如:不是 a-z、A-Z、0-9 中的字符。那么你的正则表达式会有点不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多