正则表达式匹配所有特定重复的单词

时间:2013-07-23 15:55:07

标签: c# regex

我有一个类似这样的字符串:

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

<replaced>”部分是字符串,我想匹配()之间的所有内容,因此我可以将其替换为“<replacedlist>”。< / p>

结果字符串为

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

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

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

1 个答案:

答案 0 :(得分: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>)