找出字符串中最长的数字序列

Ami*_*ble 1 c# string

我正在尝试清除低质量 OCR 读取的结果,试图删除我可以安全地认为是错误的所有内容。

所需的结果是一个 6 位数字字符串,因此我可以从结果中排除任何不是数字的字符。我也知道这些数字是按顺序出现的,所以任何乱序的数字也很可能是不正确的。

(是的,修复质量是最好的,但不......他们不会/不能更改他们的文件)

我立即Trim()删除空格,因为这些将作为文件名结束,我也删除了所有非法字符。

我已经找出了哪些字符是数字,并将它们添加到字典中,以查找它们所在的数组位置。这让我对数字序列有了清晰的视觉指示,但我正在努力研究如何让我的程序识别这一点的逻辑。

使用字符串“ Oct', 2$3622 ”进行测试(实际读取错误)理想的输出是“ 3662对人类很明显

    public String FindLongest(string OcrText)
    {
        try
        {
            Char[] text = OcrText.ToCharArray();
            List<char> numbers = new List<char>();

            Dictionary<int, char> consec = new Dictionary<int, char>();

            for (int a = 0; a < text.Length; a++)
            {
                if (Char.IsDigit(text[a]))
                {
                    consec.Add(a, text[a]);

                    // Won't allow duplicates?
                    //consec.Add(text[a].ToString(), true);
                }
            }

            foreach (var item in consec.Keys)
            {
                #region Idea that didn't work
                // Combine values with consecutive keys into new list
                // With most consecutive?
                for (int i = 0; i < consec.Count; i++)
                {
                    // if index key doesn't match loop, value was not consecutive
                    // Ah... falsely assuming it will start at 1. Won't work.
                    if (item == i)
                        numbers.Add(consec[item]);
                    else
                        numbers.Add(Convert.ToChar("#")); //string split value
                }
                #endregion
            }

            return null;
        }
        catch (Exception ex)
        {
            string message;

            if (ex.InnerException != null)
                message =
                    "Exception: " + ex.Message +
                    "\r\n" +
                    "Inner: " + ex.InnerException.Message;
            else
                message = "Exception: " + ex.Message;
            MessageBox.Show(message);

            return null;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Bri*_*sen 6

获得最长数字序列的一种快速而肮脏的方法是使用这样的正则表达式:

var t = "sfas234sdfsdf55323sdfasdf23";

var longest = Regex.Matches(t, @"\d+").Cast<Match>().OrderByDescending(m => m.Length).First();

Console.WriteLine(longest);
Run Code Online (Sandbox Code Playgroud)

这实际上将获得所有序列,显然您可以使用 LINQ 来选择其中最长的。

这不处理相同长度的多个序列。