简体   繁体   English

用其他东西替换字符串的一部分

[英]Replace part of string with something else

I would like to replace the values in a string formatted as [@ID=###] with something else. 我想用其他方式替换格式为[@ID = ###]的字符串中的值。 The string can have [@ID=###] and other things but it's the bit within the brackets that I am concerned with. 该字符串可以包含[@ID = ###]和其他内容,但这是我关注的括号中的位。 For example: 例如:

[@ID=3671818]+2 [@ ID = 3671818] +2

For that, I want to replace only "[@ID=3671818]"--the "+2" needs to stay as it is. 为此,我只想替换“ [@ ID = 3671818]”-“ +2”需要保持原样。

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? 在这种情况下,我是否需要一个startIndex变量和endIndex变量来首先删除“ [@ ID =“和”]”部分,以便我可以定位介于两者之间的内容?

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. 就学习Regex而言,这里有大量指南,我更喜欢RegExr进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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