Regex替换简单字符串
本文关键字:字符串 简单 替换 Regex | 更新日期: 2023-09-27 17:51:07
我想用正则表达式写一段代码,用它来替换括号内的ANY值。以为例
目标文本:构建(123(
build (##-build-##)
build (111)
build (xxyyzz)
在任何情况下,我都想在页面上找到单词"build(*(",并将其替换为我想要的值。
替换:
'b(build '()[^)]+('))
带有:
'1yourreplacementhere'2
使用模式(?<=build's)'([^)]*')
:
var input = "build (##-build-##)";
var result = Regex.Replace(input, @"(?<=build's)'([^)]*')", "new value");
Console.WriteLine(result);
尝试此代码,但要注意它将忽略嵌套的括号:
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)}