2

I want to replace all brackets to another in my input string only when between them there aren't digits. I wrote this working sample of code:

    string pattern = @"(\{[^0-9]*?\})";
                MatchCollection matches = Regex.Matches(inputString, pattern);
                if(matches != null)
                {
                    foreach (var match in matches)
                    {
                        string outdateMatch = match.ToString();
                        string updateMatch = outdateMatch.Replace('{', '[').Replace('}', ']');
                        inputString = inputString.Replace(outdateMatch, updateMatch);
                    }
                }

So for:

string inputString = "{0}/{something}/{1}/{other}/something"

The result will be:

inputString = "{0}/[something]/{1}/[other]/something"

Is there possibility to do this in one line using Regex.Replace() method?

2
  • Are they always separated by / or could they happen anywhere? Like for example "{0}/something{like}/{this}" ? ( No / between something and { ) Commented Oct 26, 2018 at 12:52
  • They could happen anywhere Commented Oct 26, 2018 at 12:55

3 Answers 3

2

You may use

var output = Regex.Replace(input, @"\{([^0-9{}]*)}", "[$1]");

See the regex demo.

Details

  • \{ - a { char
  • ([^0-9{}]*) - Capturing group 1: 0 or more chars other than digits, { and }
  • } - a } char.

The replacement is [$1], the contents of Group 1 enclosed with square brackets.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! That's what I was looking for!
@Piotr Great. If there can be nested braces, you could use Regex.Replace(s, @"\{(?>[^0-9{}]|(?<o>){|(?<-o>}))*(?(o)(?!))}", m => m.Value.Replace("{", "[").Replace("}", "]"))
0

Regex.Replace(input, @"\{0}/\{(.+)\}/\{1\}/\{(.+)}/(.+)", "{0}/[$1]/{1}/[$2]/$3")

1 Comment

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations!
0

Could you do this?

Regex.Replace(inputString, @"\{([^0-9]*)\}", "[$1]");

That is, capture the "number"-part, then just return the string with the braces replaced.

Not sure if this is exactly what you are after, but it seems to fit the question :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.