代码之家  ›  专栏  ›  技术社区  ›  user372724

用正则表达式替换字符串

  •  3
  • user372724  · 技术社区  · 15 年前

    我有以下情况

    案例1:

    输入: X(P)~AK,X(MV)~AK

    替换为: AP

    输出: X(P)~AP,X(MV)~AP

    案例2:

    输入: X(PH)~B$,X(PL)~B$,X(MV)~AP

    替换为 : USD$

    输出: X(PH)~USD$,X(PL)~USD$,X(MV)~USD$

    可以看出,总是 ~<string> 将被替换。

    是否可以通过正则表达式实现相同的结果?

    注意:~除了结构,在编译时什么都不知道。典型结构

    走得像

    X(<Variable Name>)~<Variable Name>
    

    我用的是C 3.0

    2 回复  |  直到 15 年前
        1
  •  5
  •   Leniel Maccaferri    15 年前

    这个简单的regex可以做到:

    ~(\w*[A-Z$])

    您可以在这里测试它:

    http://regexhero.net/tester/

    选择选项卡replace at regexhero。

    进入 ~(\W*[AZ-$]) 作为正则表达式。

    进入 ~AP 作为替换字符串。

    进入 X(P)~AK,X(MV)~AK 作为目标字符串。

    您将得到这个作为输出:

    X(P)~AP,X(MV)~AP
    

    在C习语中,您可能会遇到这样的情况:

    class RegExReplace
    {
        static void Main()
        {
            string text = "X(P)~AK,X(MV)~AK";
    
            Console.WriteLine("text=[" + text + "]");
    
            string result = Regex.Replace(text, @"~(\w*[A-Z$])", "~AP");
    
            // Prints: [X(P)~AP,X(MV)~AP]
            Console.WriteLine("result=[" + result + "]");
    
            text = "X(PH)~B$,X(PL)~B$,X(MV)~AP";
    
            Console.WriteLine("text=[" + text + "]");
    
            result = Regex.Replace(text, @"~(\w*[A-Z$])", "~USD$");
    
            // Prints: [X(PH)~USD$,X(PL)~USD$,X(MV)~USD$]
            Console.WriteLine("result=[" + result + "]");
        }
    }
    
        2
  •  0
  •   Wesley Wiser    15 年前

    为什么不使用string.replace(string,string)?