用{0},{1}等替换字符串中的\ [... \]和\(... \)块

时间:2013-12-10 19:14:23

标签: c# regex

我有以下字符串:

"Some text \[(2 \cdot 3) = 6\] and more text and \((2^3) = 8\)" ...

如何用\[ ... \]\( ... \){0}等替换{1}{2}块,并将删除的块放在字符串数组中?

谢谢你, 米格尔

3 个答案:

答案 0 :(得分:2)

您可以使用以下正则表达式:

string input = @"Some text \[(2 \cdot 3) = 6\] and more text and \((2^3) = 8\)";
string pattern = @"\\\[.*\\\]|\\\(.*\\\)";
int index = 0;
string result = Regex.Replace(input, pattern, 
                              match => string.Format("{{{0}}}", index++));

如果您想记住哪些文字被哪种模式取代,您可以记住所有匹配项:

var matches = Regex.Matches(input, @"\\\[.*\\\]|\\\(.*\\\)")
                   .Cast<Match>()
                   .Select((match, i) => new
                   {
                       Key = string.Format("{{{0}}}", i),
                       Text = match.Value
                   });

他们用这种或那种方式替换一个简单的字符串:

foreach (var match in matches)
{
    input = input.Replace(match.Text, match.Key);
}

答案 1 :(得分:0)

是的,这很有道理。你需要使用捕获组,如果你需要格外小心,你需要确保你用作替代的标记(例如{0})不会出现在你正在处理的文本。

有关如何在C#中指定和引用反向引用的信息,请参阅http://msdn.microsoft.com/en-us/library/thwdfzxy(v=vs.110).aspx

答案 2 :(得分:0)

我不知道是否有一种纯正的正则表达式来替换具有递增值的组,但毫无疑问,具有比我更好的正则表达式的人会知道。

查找包含在转义方括号或转义的parens中的组的正则表达式可能如下所示:

(\\\[.*]|\\\(.*\))

http://rubular.com/r/uRePwMuWIV

获得模式后,您应该能够使用Regex类逐步替换这些组。

相关问题