简体   繁体   中英

Replace part of string with something else

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM