3

我有一个字符串是这样的:

SELECT * FROM blah WHERE ID IN ('<replaced>', '<replaced>', '<replaced>')

其中“ <replaced>”部分是一个字符串,我想匹配它们之间的所有内容()所以我可以用“”替换它<replacedlist>

结果字符串将是

SELECT * FROM blah WHERE ID IN (<replacedList>)

我不想只在括号内做所有事情,因为这将匹配其他字符串,只有当括号包含“ <replaced>”并且它重复任意次数时。

如果它是相关的,我将使用 C# 来解析它,但我没有标记它,因为这应该是一般的正则表达式。

4

1 回答 1

2

你可以使用这种模式:

(?<=\([^)]*)'<replaced>'(, '<replaced>')*(?=[^)]*\))

如在

var input = "SELECT * FROM blah WHERE ID IN ('<replaced>', '<replaced>', '<replaced>')";
var pattern = @"(?<=\([^)]*)'<replaced>'(, '<replaced>')*(?=[^)]*\))";
var output = Regex.Replace(input, pattern, "<replacedList>");

Console.WriteLine(output); // SELECT * FROM blah WHERE ID IN (<replacedList>)

或者,您可以使用此模式:

(\([^)]*?)(<replaced>(?:, <replaced>)*)([^)]*\))

如:

var input = "SELECT * FROM blah WHERE ID IN ('<replaced>', '<replaced>', '<replaced>')";
var pattern = @"(\([^)]*?)('<replaced>'(?:, '<replaced>')*)([^)]*\))";
var output = Regex.Replace(input, pattern, "$1<replacedList>$3");

Console.WriteLine(output); // SELECT * FROM blah WHERE ID IN (<replacedList>)
于 2013-07-23T16:01:08.257 回答