正则表达式转换C#中的输入

时间:2012-12-23 16:40:36

标签: regex c#-4.0

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        try
        {
            using (StreamReader sr = new StreamReader("TestFile.txt"))
            {
                String line = sr.ReadToEnd();
                Console.WriteLine(line);
            }

            string pattern1 = @"(in cm)";
            string pattern2 = @"mm";
            Regex rgx1 = new Regex(pattern1);
            Regex rgx2 = new Regex(pattern2);
            Regex rgx3 = new Regex(pattern3);
        }
        catch (Exception e)
        {
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}   

如何在C#中使用正则表达式将以下cm从文件转换为m:

rectangle (in cm) 20 H * 40 W and circle diameter 30 mm 

1 个答案:

答案 0 :(得分:0)

在Main()中使用这样的内容。

    string s1="", s2;
    try
    {
        using (StreamReader sr = new StreamReader("C:\\test.txt")) //in my case
        {
            s1 = sr.ReadToEnd();
        }

    }
    catch (Exception ei) { MessageBox.Show(ei.Message); }

    Console.WriteLine(s1);

    Regex r = new Regex(@"\bcm\b");  //regex for changing pattern
    s2 = r.Replace(s1, "m");

    Console.WriteLine(s2);