c#在字符串str1中找到".PID()"并修改为".PID[]",其中括号能会有很多其他的内容,例如字符串"a.PID(b.PID.d)(e)",修改后的内容为"a.PID[b.PID.d](e)"。求实例代码。C#正则表达式

解决方案 »

  1.   

    最好用正则,不用正则,用下面笨方法也可以
     int i = str1.IndexOf('(');
                int j = str1.IndexOf(')', i + 1);
                while (i >= 0 && j > i)
                {
                    str1 = str1.Substring(0, i - 1) + "[" + str1.Substring(i + 1, j - i - 1) + "]" + str1.Substring(j + 1);
                    i = str1.IndexOf('(');
                    j = str1.IndexOf(')', i + 1);
                }
      

  2.   

    这个不行啊,这个将所有的()都替换了,我只需要替换.PID后面的()。
      

  3.   

    哦,不好意思,没加.pid,我改下
      

  4.   

     string str1 = "abc.PID(123)a.PID(123)";
                int i = str1.IndexOf(".PID(");
                int j = str1.IndexOf(')', i + 1);
                while (i >= 0 && j > i)
                {
                    i = i + 4;
                    str1 = str1.Substring(0, i - 1) + "[" + str1.Substring(i + 1, j - i - 1) + "]" + str1.Substring(j + 1);
                    i = str1.IndexOf(".PID(");
                    j = str1.IndexOf(')', i + 1);
                }
      

  5.   

    第一行string str1 = "abc.PID(123)a.PID(123)";是测试代码,你注释掉
      

  6.   

    主要是括号中的内容是不确定的,如果再出现(),例如".PID(A()())",那就不能完成替换了。
      

  7.   

    正则不太会,表达式是不是写成.PID(/w)?再就是这是匹配,匹配到了再如何替换呢?求实例。。
      

  8.   

    正则我也不会,只好继续提供笨方法,这回括号里有括号可以解决了
    int i = str1.IndexOf(".PID(");
                int j=0;
                while (i >= 0)
                {
                    i = i + 4;
                    int x = 0;
                    for (int n = i + 1; n < str1.Length; n++)
                    {
                        if (str1[n] == '(')
                            x++;
                        if (str1[n] == ')')
                        {
                            if (x == 0)
                            {
                                j = n;
                                break;
                            }
                            x--;
                        }
                    }
                    if(j>i)
                       str1 = str1.Substring(0, i - 1) + "[" + str1.Substring(i + 1, j - i - 1) + "]" + str1.Substring(j + 1);
                    i = str1.IndexOf(".PID(",i+1);
                }