Reputation: 103
My starting string looks like this:
This is (a test) of (something (cool like) this and) stuff like ((that and) stuff) yeah.
and I want to transform it into this:
This is (a test) of (something [cool like] this and) stuff like ([that and] stuff) yeah.
Any parentheses within parentheses needs to be changed to brackets []. Anything else just stays the same as it is. It will not need to go recursive and will only be one level deep ever like in the example... if that helps.
So far with my string function I can only get it find a first parentheses, so I really have no sample code. :-/
static String CorrectBrackets(String stringToCorrect)
{
int firstParenIdx = stringToCorrect.IndexOf('(');
return stringToCorrect;
}
Also, if this can be done without RegEx, I am just fine with that!
Upvotes: 0
Views: 410
Reputation: 487
You can also use this Regex:
(?<=\().*(?<bracket>\([^\(]*\)).*(?=\))
with the Ungreedy flag.
you should replace the Group "bracket" replacing the first and last characters by [ and ]
Upvotes: 1
Reputation: 3937
This should do it:
static readonly Regex regex = new Regex(@"\([^\(^\).]*(?<bracket>\([^\(^\).]+\))[^\(^\).]*\)");
static string ReplaceInnerParens(Match match)
{
return match.Value.Replace(match.Groups["bracket"].Value, "[" + match.Groups["bracket"].Value.Substring(1, match.Groups["bracket"].Value.Length - 2) + "]");
}
static string Replace(string input)
{
return regex.Replace(input, new MatchEvaluator(ReplaceInnerParens));
}
void Main() {
Console.WriteLine(Replace("This is (a test) of (something (cool like) this and) stuff like ((that and) stuff) yeah."));
}
Upvotes: 1
Reputation: 20732
Indeed, this can be done without RegEx in a very straightforward way:
Iterate over all characters and remember the nesting level of parentheses. If you are already at nesting level 1 and find any other opening or closing parentheses, replace them.
Untested, but hopefully illustrative:
static string CorrectBrackets(string strString)
{
var result = new System.Text.StringBuilder(strString);
int bracketLevel = 0;
for (int i = 0; i < result.Length; i++) {
switch (result[i]) {
case '(':
bracketLevel++;
if (bracketLevel >= 2) {
result[i] = '[';
}
break;
case ')':
bracketLevel--;
if (bracketLevel >= 1) {
result[i] = ']';
}
break;
}
return result.ToString();
}
Upvotes: 1
Reputation: 27095
This will do it if you don't want to use a Regex, it counts the indentation level and switches brackets with square brackets if the indentation level is more than one.
private static string CorrectBrackets(string text)
{
StringBuilder builder = new StringBuilder(text);
int nestingLevel = 0;
for (int i = 0; i < builder.Length; i++)
{
switch (builder[i])
{
case '(':
if (nestingLevel > 0) builder[i] = '[';
nestingLevel++;
break;
case ')':
if (nestingLevel > 1) builder[i] = ']';
nestingLevel--;
break;
default: break;
}
}
return builder.ToString();
}
Upvotes: 1