无法获得 return 的正确索引

Can't get the proper Index to return

好的,首先我要感谢大家在过去几周内对我的帮助,这是另一个!!!

我有一个文件,我正在使用 Regex 查找术语 "TamedName" 出现了多少次。这是简单的部分:)

本来我是这样设置的

            StreamReader ff = new StreamReader(fileName);
        String D = ff.ReadToEnd();
        Regex rx = new Regex("TamedName");
        foreach (Match Dino in rx.Matches(D))
        {
            if (richTextBox2.Text == "")
                richTextBox2.Text += string.Format("{0} - {1:X} - {2}", Dino.Value, Dino.Index, ReadString(fileName, (uint)Dino.Index));
            else
                richTextBox2.Text += string.Format("\n{0} - {1:X} - {2}", Dino.Value, Dino.Index, ReadString(fileName, (uint)Dino.Index));
        }

它返回的索引点完全不正确,如图所示

我相当有信心我知道它为什么这样做,可能是因为将所有内容从二进制文件转换为字符串,显然不是所有的字符都会被翻译,所以这会抛出实际的索引计数,所以试图relate back 根本不起作用...问题是,我不知道如何将 Regex 与二进制文件一起使用并正确翻译:(

我正在使用 Regex 与简单的搜索函数,因为 "TamedName" 的每次出现之间的差异太大而无法编码到函数中。

真的希望你们能帮我解决这个问题:(我运行没主意了!!

问题是您正在读取二进制文件,流读取器在将其读入 Unicode 字符串时会进行一些解释。需要按字节处理。

我的代码如下。(仅供参考,您需要启用不安全编译才能编译代码 - 这是为了允许快速搜索二进制数组)

为了正确归属,我借用了这个 SO answer by Dylan Nicholson

的字节版本的 IndexOf
namespace ArkIndex
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = "TheIsland.ark";
            string searchString = "TamedName";
            byte[] bytes = LoadBytesFromFile(fileName);
            byte[] searchBytes = System.Text.ASCIIEncoding.Default.GetBytes(searchString);

            List<long> allNeedles = FindAllBytes(bytes, searchBytes);    
        }

        static byte[] LoadBytesFromFile(string fileName)
        {
            FileStream fs = new FileStream(fileName, FileMode.Open);
            //BinaryReader br = new BinaryReader(fs);
            //StreamReader ff = new StreamReader(fileName);

            MemoryStream ms = new MemoryStream();
            fs.CopyTo(ms);
            fs.Close();
            return ms.ToArray();   
        }

        public static List<long> FindAllBytes(byte[] haystack, byte[] needle)
        {
            long currentOffset = 0;
            long offsetStep = needle.Length;
            long index = 0;
            List<long> allNeedleOffsets = new List<long>();
            while((index = IndexOf(haystack,needle,currentOffset)) != -1L)
            {
                allNeedleOffsets.Add(index);
                currentOffset = index + offsetStep;
            }
            return allNeedleOffsets;
        }

        public static unsafe long IndexOf(byte[] haystack, byte[] needle, long startOffset = 0)
        {
            fixed (byte* h = haystack) fixed (byte* n = needle)
            {
                for (byte* hNext = h + startOffset, hEnd = h + haystack.LongLength + 1 - needle.LongLength, nEnd = n + needle.LongLength; hNext < hEnd; hNext++)
                    for (byte* hInc = hNext, nInc = n; *nInc == *hInc; hInc++)
                        if (++nInc == nEnd)
                            return hNext - h;
                return -1;
            }
        }    
    }
}