且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正则表达式选择两个“字符串”

更新时间:2022-03-29 22:47:01

这是一种没有RegEx的方法:



Here is a way to do it without RegEx:

    class Program
    {
        static void Main(string[] args)
        {

            string fileName = "CheckFileList.txt";
            Dictionary<string,List<string>> sections = GenerateList(fileName);

            foreach (string sectionName in sections.Keys)
            {
                foreach (string file in sections[sectionName])
                    Console.WriteLine(string.Format("Section {0} : File {1}", sectionName, file));
            }

            Console.ReadKey();
        }

        public static Dictionary<string,List<string>> GenerateList(string fileName)
        {
            string[] fileLines = File.ReadAllLines(fileName);

            string currentSection = string.Empty;
            Dictionary<string,List<string>> retVal = new Dictionary<string,List<string>>();

            for (int i = 0; i < fileLines.Length; i++)
            {
                if (fileLines[i].StartsWith("["))
                {
                    if (string.IsNullOrEmpty(currentSection))
                    {
                        currentSection = fileLines[i].TrimStart('[').TrimEnd(']');
                        retVal[currentSection] = new List<string>();
                    }
                    else
                    {
                        if (fileLines[i].StartsWith("[/"))
                            currentSection = string.Empty;
                        else
                            throw new Exception("Invalid section identifier " + fileLines[i] + " line " + i);
                    }
                    continue;
                }

                if (!string.IsNullOrEmpty(currentSection))
                    retVal[currentSection].Add(fileLines[i]);
            }

            return retVal;
        }
    }
</string>





字典包含文件中的部分作为键,然后是列表该部分中的文件。这也可扩展到更多部分或不同名称。



我认为它比RegEx更易于维护。



The dictionary contains the sections in the file as keys, and then a list of files in that section. This is also expandable to more sections or different names.

And I think its much more maintainable than a RegEx.