1

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?

4
  • Sounds like you're making a lot of work for yourself. Instead of removing and prepending characters, why not just create a new string and append "+2" to it? Commented Nov 5, 2014 at 20:07
  • @BobKaufman I'm not sure I know what you mean...? Do you mean I should use a Split() at some point? Commented Nov 5, 2014 at 20:09
  • If all you want is to create a string that ends with "+2", why don't you just do that rather than deleting characters from a string and inserting new ones? Commented Nov 5, 2014 at 20:18
  • The "+2" is just an example. It could be "*3" or "+2*1.5" or "/5" or it could just be the value in the brackets. Commented Nov 5, 2014 at 20:53

1 Answer 1

6

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.