正则表达式替换简单字符串

时间:2013-01-10 01:09:04

标签: c# .net regex

我想用正则表达式编写一段代码,让我在括号内替换任何值。采取以下案例

目标文字:build(123)

build (##-build-##)
build (111)
build (xxyyzz)

在所有情况下,我想在页面上找到“build( * )”一词,并将其替换为我想要的值。

3 个答案:

答案 0 :(得分:2)

替换:

\b(build \()[^)]+(\))

使用:

\1yourreplacementhere\2

答案 1 :(得分:1)

试试这段代码,但要注意它会忽略嵌套的括号:

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)}

答案 2 :(得分:1)

使用模式(?<=build\s)\([^)]*\)

var input = "build (##-build-##)";

var result = Regex.Replace(input, @"(?<=build\s)\([^)]*\)", "new value");

Console.WriteLine(result);