1

我有一个字符串如下:

{a{b,c}d}

如果我给 1,则字符串必须显示为:

{a d} 

内大括号内的内容应与大括号一起删除。

有人可以帮我吗?

4

3 回答 3

5

要提取 {} 的内部分组,请使用以下正则表达式:

string extract = Regex.Replace(source, "\{\w(\{\w,\w\})\w\}", "$1");

实际上,如果您想删除逗号....

string extract = Regex.Replace(source, "\{\w\{(\w),(\w)\}\w\}", "{$1 $2}");

要在没有内部分组的情况下提取外部:

string extract = Regex.Replace(source, "(\{\w)\{\w,\w\}(\w\})", "$1 $2");

如果在您的示例中 a、b、c、d 不是字面上的单个字符,即字母组甚至空格等,请将\w替换为\w+甚至.*

根据您对嵌套的评论....

string extract = Regex.Replace(source, "(\{\w)\{.*\}(\w\})\w*", "$1 $2");
于 2010-07-30T08:58:40.483 回答
1

去上面的正则表达式方式......它真的更漂亮!


你可以用手来做......几年前我在一个例子中写了一些东西......必须寻找它......:

     string def = "1+2*(3/(4+5))*2";
     int pcnt = 0, start = -1, end = -1;
     bool subEx = false;
     if(def.Contains("(") || def.Contains(")"))
        for(int i = 0; i < def.Length; i++) {
           if(def[i] == '(') {
              pcnt++;
              if(!subEx)
                 start = i;
           } else if(def[i] == ')')
              pcnt--;
           if(pcnt < 0)
              throw new Exception("negative paranthesis count...");
           if(pcnt != 0)
              subEx = true;
           if(subEx && pcnt == 0 && end == -1)
              end = i;
        }
     if(pcnt != 0) {
        throw new Exception("paranthesis doesn't match...");
     }
     if(subEx) {
        string firstPart = def.Substring(0, start);
        string innerPart = def.Substring(start + 1, end - (start + 1));
        string secondPart = def.Substring(end + 1);
        Console.WriteLine(firstPart);
        Console.WriteLine(innerPart);
        Console.WriteLine(secondPart);
     }

写道:

1+2*
3/(4+5)
*2
于 2010-07-30T08:53:39.937 回答
0

命名空间分隔符 { 类程序 { 静态无效 Main(string[] args) { string src = "a{b{c{d,e}f}g}h"; int发生计数= 0;foreach (char ch in src) { if(ch == '{') {occurrenceCount++; } } Console.WriteLine("输入要删除块的编号:"); 整数给定值 = 0; CheckValid(out givenValue);

        int removeCount = occurenceCount + 1 - givenValue;
        occurenceCount = 0;
        int startPos = 0;
        for (int i = 0; i < src.Length; i++)
        {
            if (src[i] == '{')
            {
                occurenceCount++;
            }   
            if(occurenceCount == removeCount)
            {
                startPos = i;
                break;
                //i value { of to be removed block
            }
        }
        int endPos = src.IndexOf('}', startPos);
        src = src.Remove(startPos,endPos);

        //index of }
        Console.WriteLine("after reved vale:" + src);
        Console.ReadKey();
    }

    public static void CheckValid(out int givenValue)
    {
        if (!int.TryParse(Console.ReadLine(), out givenValue))
        {
            Console.WriteLine("Enter a valid no. to remove block: ");
            CheckValid(out givenValue);
        }
    }
}

}

于 2010-08-03T10:20:02.440 回答