C#中部分正则表达式的使用

前几天打算解析一个文本文件,发现在处理的过程中利用string一类的就行文本和数字的一些解析感觉很麻烦,觉得应该用正则表达式会更容易点,且效率较高。

如解析“从第8至第15题”,我需要算出这个是包含了8个题目,代码如下:

public static int isZhi(string txt)
{
    Match m = Regex.Match(txt, @"\d+至第?\d+");
    if (m.Success)
    {
        string[] ss1 = Regex.Split(m.ToString(), @"至第?");
        int n = Convert.ToInt32(ss1[1]) - Convert.ToInt32(ss1[0]) + 1;
        return n;
    }
    else
    {
        m = Regex.Match(txt, @"\d+、\d+");
        if (m.Success)
        {
            string[] ss1 = Regex.Split(m.ToString(), @"、");
            int n = Convert.ToInt32(ss1[1]) - Convert.ToInt32(ss1[0]) + 1;
            return n;
        }
        else
        {
            m = Regex.Match(txt, @"\d+和第\d+");
            if (m.Success)
            {
                return 2;
            }
        }
    }
    return 0;
}

要解析“

1. C      2. C      3. B      4. A      5. B      6. A      7. B      8. C      9. C    10. A
11. A    12. B    13. B    14. C    15. C    16. B    17. A    18. B    19. C    20. A”

中的后面的答案到列表中,则代码如下:

public static List<string> handle(string[] ss)
{
    List<string> list = new List<string>();
    for (int i = 0; i < ss.Length; ++i)
    {
        string txt = ss[i].Trim();
        Match m = Regex.Match(txt, @"\d+\.\s[A-Z]");
        while (m.Success)
        {
            string s = m.ToString();
            string[] ss1 = Regex.Split(s, @"\s");
            list.Add(ss1[1]);
            m = m.NextMatch();
        }
    }

    return list;
}

解析1M1QZ2CZ

public Dictionary<string, int> handle(string txt)
    {
        Dictionary<string, int> d = new Dictionary<string, int>();
        Match m = Regex.Match(txt, @"\d+[a-zA-Z]+");
        while (m.Success)
        {
            string s = m.ToString();
            string type = s.Substring(s.Length - 1);
            string value = s.Substring(0, s.Length - 1);
            Match m1 = Regex.Match(s, @"\d+");
            if (m1.Success)
            {
                value = m1.ToString();
            }
            Match m2 = Regex.Match(s, @"[a-zA-Z]+");
            if (m2.Success)
            {
                type = m2.ToString();
            }
            int n = 0;
            if (Int32.TryParse(value, out n) == true)
            {
                if (d.ContainsKey(type) == true)
                    d[type] += n;
                else
                    d.Add(type, n);
            }
            m = m.NextMatch();
        }

        return d;
    }
 

嗯,真是不错,就这么简单,让我节省了很多的时间。

尤其注意的是,学习正则表达式一定要知道一些基本的匹配模式。

原文地址:https://www.cnblogs.com/tianfu/p/1702056.html