我想使用正则表达式编写一段代码,让我替换括号内的任何值。采取以下案例
目标文本:构建 (123)
build (##-build-##)
build (111)
build (xxyyzz)
在所有情况下,我都想在页面上找到“build ( * )”这个词,并将其替换为我想要的值。
代替:
\b(build \()[^)]+(\))
和:
\1yourreplacementhere\2
试试这个代码,但要注意它会忽略嵌套括号:
var pattern = @"build \((.+)\)";
var regex = new Regex(pattern);
string[] strings =
{
"build (##-build-##)",
"build (111)",
"build (xxyyzz)"
};
var results = strings.
Select(s => regex.Replace(s, "(foo)")).
ToArray();
//results = {build (foo), build(foo), build(foo)}
使用模式(?<=build\s)\([^)]*\)
:
var input = "build (##-build-##)";
var result = Regex.Replace(input, @"(?<=build\s)\([^)]*\)", "new value");
Console.WriteLine(result);