Reputation: 65
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?
Upvotes: 2
Views: 128
Reputation: 1
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 :)
Upvotes: 0
Reputation: 10591
Regex.Replace(input, @"\{0}/\{(.+)\}/\{1\}/\{(.+)}/(.+)", "{0}/[$1]/{1}/[$2]/$3")
Upvotes: 0
Reputation: 626689
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.
Upvotes: 2