1
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 
4

1 回答 1

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);
于 2012-12-23T17:20:51.820 回答