Remove delimiter using C#
I Have a string as开发者_开发百科 follows:
{a{b,c}d}
if i give 1, the string must be displayed as:
{a d}
the content within inner braces should be removed along with the braces.
Can anyone help me with it?
To extract the inner grouping of {} use the following regular expression:
string extract = Regex.Replace(source, "\{\w(\{\w,\w\})\w\}", "$1");
Actually, if you want to remove the comma....
string extract = Regex.Replace(source, "\{\w\{(\w),(\w)\}\w\}", "{$1 $2}");
To extract the outer without the inner grouping:
string extract = Regex.Replace(source, "(\{\w)\{\w,\w\}(\w\})", "$1 $2");
if in your example a, b, c, d are not literally single characters, that is groups of letters or even spaces, etc replace \w with \w+ or even .*
based on your comment on nesting....
string extract = Regex.Replace(source, "(\{\w)\{.*\}(\w\})\w*", "$1 $2");
go the regex-way above... it's really more beautiful!
you could do it by hand... i've written something for paranthesis in an example a few years ago... have to look for it a sec...:
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);
}
writes:
1+2*
3/(4+5)
*2
namespace Delimiter { class Program { static void Main(string[] args) { string src = "a{b{c{d,e}f}g}h"; int occurenceCount = 0; foreach (char ch in src) { if(ch == '{') { occurenceCount++; } } Console.WriteLine("Enter a no. to remove block: "); int givenValue = 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);
}
}
}
}
精彩评论