在regex中没有任何内容替换所有已命名的捕获组

时间:2012-07-30 22:08:28

标签: c# regex replace

假设我有这个主题:

////////File description////////
Name: SomeFile.cs
Size: 234
Description: Foo
Date: 08.14.2012
///////////////////////////////

如何让该主题变成:

////////File description////////
Name: 
Size: 
Description: 
Date:
///////////////////////////////

现在我执行以下操作:

var pattern = 
@"(/+File description/+
Name: )(?<name>.+)(
Size: )(?<size>.+)(
Description: )(?<des>.+)(
Date: )(?<date>.+)(
/+)";

// subject = fist code at top of this questoin

var temp = Regex.Replace(subject,pattern,"$1$2$3$4$5");

模式非常混乱



现在我的问题是:

我希望有这样的模式:

/+File description/+
Name: (?<name>.+)
Size: (?<size>.+)
Description: (?<des>.+)
Date: (?<date>.+)
/+

我想知道是否可以替换群组namesize。什么都没有

2 个答案:

答案 0 :(得分:0)

您可以简单地使用空描述重写该文件,除非您在同一文件中有多个主题。

您可以通过以下方式执行此操作:

string text = "/////////////File description/////////////\nName:\nSize:\nDescription:\nDate:\n//////////////////////////";
System.IO.File.WriteAllText(@"X:\Path\to\your\file.whatever", text);

答案 1 :(得分:0)

这可能比您想要的更复杂,但您可以尝试使用MatchEvaluator。 MatchEvaluator计算每个匹配的替换字符串。并且MatchEvaluator可以访问“匹配”对象,所以它可以做一些有趣的事情,仅受你想象力的限制......

        var pattern =
@"/+File description/+ 
Name: (?<name>.+) 
Size: (?<size>.+) 
Description: (?<des>.+) 
Date: (?<date>.+) 
/+";
        var temp = Regex.Replace(data, pattern, new MatchEvaluator(eval));
        Console.WriteLine("{0}", temp);
    //...
    string eval(Match mx)
    {
        Stack<Group> stk = new Stack<Group>();
        for(int i=1; i<mx.Groups.Count; ++i)
            stk.Push(mx.Groups[i]);

        string result = mx.Groups[0].Value;
        int offt = mx.Index;
        while(stk.Count > 0)
        {
            var g = stk.Pop();
            int index = g.Index - offt;
            result = result.Substring(0,index) + result.Substring(index+g.Length);
        }
        return result;
    }

使用MatchEvaluator的另一种方法看起来像这样(并且应该适用于您的模式或我的模式)。

    string eval2(Match mx)
    {
        string data = mx.Value;
        data = Regex.Replace(data, "Name: .+", "Name: ");
        data = Regex.Replace(data, "Size: .+", "Size: ");
        data = Regex.Replace(data, "Description: .+", "Description: ");
        data = Regex.Replace(data, "Date: .+", "Date: ");
        return data;
    }

这是有效的,因为您在匹配中替换。即,你的外部比赛缩小了搜索范围,而你的个人替换者没有机会替换错误的东西。如果使用这种方法,外部模式可以更简单,因为不需要组。