正则表达式.NET问题

Win*_*rms 2 c# regex

是否可以使用Regex.Replace匹配字符串,但只替换匹配字符串的一部分?某些方法来标记应该用替换文本参数替换的字符串的一部分?

SLa*_*aks 5

您可以使用组来插入原始字符串的一部分,也可以使用lookbehind和lookahead.

例子

使用组:

someString = Regex.Replace(someString, @"(before)content(after)", "$1new content$2");
Run Code Online (Sandbox Code Playgroud)

使用环视:

someString = Regex.Replace(someString, @"(?<=before)content(?=after)", @"new content");
Run Code Online (Sandbox Code Playgroud)