【问题标题】:Delete the last instance of a certain string from a text file without changing the other instances of the string从文本文件中删除某个字符串的最后一个实例而不更改该字符串的其他实例
【发布时间】:2011-02-22 02:48:06
【问题描述】:

我有一个 C# 程序,我在其中使用大量 RegEx.Replace 来替换文本文件中的文本。

这是我的问题。

在我的文本文件中,我有一个代码,例如“M6T1”。此代码列在文本文件的许多地方。

但是,我只想从文本文件的底部(最后一个实例)删除它。文本文件的底部总会有一个“M6T1”,但并不总是最后一行。它可能是从底部算起的第 3 行、从底部算起的第 5 行等。

我只想删除“M6T1”的最后一个实例,因此 RegEx.Replace 在这里不起作用。我不想干扰文本文件中其他位置的其他“M6T1”。

有人可以帮我解决这个问题吗?

谢谢

【问题讨论】:

    标签: c# regex string text replace


    【解决方案1】:

    由于我的分数很低,我不能对 kevingessner 的回答发表评论。所以,我将在这里添加我的评论,并修改他的代码 -

    var needle = "M6T1";
    var ix = str.LastIndexOf(needle);
    str = str.Substring(0, ix) + str.Substring(ix + needle.Length);
    

    当 needle 的索引 = -1 时,这可能会导致异常。当在字符串/干草堆中找不到针时,就会发生这种情况。为了避免这种情况,我这样做了 -

    String needle = "M6T1";
    int ix = str.LastIndexOf(needle);
    if(ix != -1){
          str = str.Substring(0, ix) + str.Substring(ix + needle.Length); 
    }else{//not found}
    

    【讨论】:

      【解决方案2】:

      很遗憾,无法附上回复。

      但是看 http://msdn.microsoft.com/en-us/library/vstudio/ms229012%28v=vs.100%29.aspx http://msdn.microsoft.com/en-us/library/vstudio/ms229004%28v=vs.100%29.aspx

      用于命名约定。你不想把参数写成大写。否则你可能会与属性发生冲突,看看这些属性通常是如何用大写驼峰写的。这可能会导致一些混乱

      【讨论】:

        【解决方案3】:
        public static string ReplaceFirstOccurrence (string Source, string Find, string Replace)
        {
            int Place = Source.IndexOf(Find);
            string result = Source.Remove(Place, Find.Length).Insert(Place, Replace);
            return result;
        }
        
        public static string ReplaceLastOccurrence(string Source, string Find, string Replace)
        {
            int Place = Source.LastIndexOf(Find);
            string result = Source.Remove(Place, Find.Length).Insert(Place, Replace);
            return result;
        }
        

        【讨论】:

          【解决方案4】:
          var needle = "M6T1";
          var ix = str.LastIndexOf(needle);
          str = str.Substring(0, ix) + str.Substring(ix + needle.Length);
          

          【讨论】:

          • +1 for needle(虽然我认为是 完美 str 应该是 haystack :)
          • @egrunin - 使用 needlehaystack 是 PHP 为数不多的正确做法之一。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-11-13
          • 2014-09-15
          • 1970-01-01
          • 2018-09-23
          • 1970-01-01
          • 2021-02-09
          • 2014-03-19
          相关资源
          最近更新 更多