如何使用通配符删除字符串的特定部分?

Bob*_*ob. 1 c# regex string

目前,我使用:

Variabls:

 int recordCount = 5;
 Header = "Index"; // Can also be "Starting Index"
Run Code Online (Sandbox Code Playgroud)

标题:

 Header = Header.Split(' ')[0] + " (" + recordCount + ")";
Run Code Online (Sandbox Code Playgroud)

变化:

 Index (5)
Run Code Online (Sandbox Code Playgroud)

至:

 Index (6)
Run Code Online (Sandbox Code Playgroud)

当我想用新的Header替换Header时,我使用了上面的内容,但问题是当我开始使用多个单词时,Header它会删除Header Name的其余部分.即当它说Starting Index:它只显示Starting.

我可以使用正则表达式来简单地查找括号之间的值并将其替换为另一个变量吗?

J0H*_*0HN 5

Regex re = new Regex(@"\(\w+\)");
string input = "Starting Index: (12asd)";
string replacement = "12ddsa";
string result = re.Replace(input, replacement);
Run Code Online (Sandbox Code Playgroud)

如果你需要执行更复杂的替换(即如果替换取决于大括号之间的捕获值),你将不得不坚持使用Regex.Match方法

更新:Match事情很快变得丑陋:)

 Regex re = new Regex(@"^(.*)\((\w+)\)\s*$");
 string input = "Starting Index: (12)";
 var match = re.Match(input);

 string target = match.Groups[2].Value;
 //string replacement = target + "!!!!"; // general string operation
 int autoincremented = Convert.ToInt32(target) + 1; // if you want to autoincrement

 string result = String.Format("{0}: ({1})", match.Groups[1].Value, autoincremented);
Run Code Online (Sandbox Code Playgroud)