Reputation: 1569
I would like to replace the values in a string formatted as [@ID=###] with something else. The string can have [@ID=###] and other things but it's the bit within the brackets that I am concerned with. For example:
[@ID=3671818]+2
For that, I want to replace only "[@ID=3671818]"--the "+2" needs to stay as it is.
I would like to try something like this:
value = value.Replace().Insert();
But I know that won't work. Is there a way to do this in one line of code or do I need to work with various string variables? As in, do I need a startIndex variable and endIndex variable to remove the "[@ID=" and "]" pieces first so I can target just what is in between?
Upvotes: 1
Views: 219
Reputation: 25370
This is what Regular Expressions are for:
string str = @"[@ID=3671818]+2";
var newStr = Regex.Replace(str, @"\[.*\]", "TEST");
Console.WriteLine(newStr);
//newStr = "TEST+2"
Everything within brackets (including the brackets) will be replaced with your replacement string.
If you want to keep the brackets, you'd use
@"(?<=\[).*(?=\])" //newStr = "[TEST]+2"
which uses lookaheads and lookbehinds to find text within brackets, and replace that text.
As far as learning Regex, there are a ton of guides out there, and I prefer RegExr for testing them.
Upvotes: 6