字符串如何使用通配符和正则表达式来替换\?
譬如:
    字符串:“中之国美的国”
    想把: “中之国”替换成“中国”,把“美的国”替换成“美国”。
           a. 想用通配符来进行,譬如替换 "?国"为"国"则可实现上面的结果。
              注:? 代表一个字, * 代表任意字符串.
              该如何做?
           b.用正则表达式该如何进行字符串替换操作?

解决方案 »

  1.   

    用 Regex.Replace这个正则表达式该如何写啊?
      

  2.   

    正则表达式中,小数点(.)匹配任意一个字符,相当于通配符中的问号(?)
    正则表达式中,".*"表示任意字符重复任意次,相当于通配符中 "*"代码:
    Regex.Replace( str, ".国", "国" );更多帮助,欢迎参考正则表达式帮助文档:(推荐,尤其入门推荐)
    http://www.regexlab.com/zh/regref.htm
      

  3.   

    using System;
    using System.Collections;
    using System.Text.RegularExpressions;public class MyClass
    {
    public static void Main()
    {
    String text = "中之国美的国";
    String pattern = "\\w国";
    Regex r = new Regex(pattern, RegexOptions.IgnoreCase);

    Console.WriteLine("-------------- RESULT -------------");
    MatchEvaluator myEvaluator = new MatchEvaluator(MyClass.GetReplaceResult);

    Console.WriteLine("原字符串:");
    Console.WriteLine(text);

    text = r.Replace(text,myEvaluator);
    Console.WriteLine("替换后的字符串:");
    Console.WriteLine(text);

    Console.ReadLine();
    }

    public static string GetReplaceResult(Match m)
        {
    //Console.WriteLine(m.Value);
            return Regex.Replace(m.Value, "\\w国", "国");
        }

    }
      

  4.   

    Regex.Replace( str, ".国", "国" );
    用这个就可以了。。
    .代表任意单字符(除换行符外)
    .*代表任意字符串(包括空字符串)。。
    .+代表任意非空字符串