替换最后一个特定字符串



我有一个这样的字符串:

string myText = "abc def ghi 123 abc def ghi 123 abc def";

我只想用空替换最后一个abc

这是我的代码:

string pattern2 = "([abc])$";
string replacement2 = "";
Regex regEx = new Regex(pattern2);
var b = Regex.Replace(regEx.Replace(myText, replacement2), @"s", " ");

不能正常工作,那么它怎么能做到呢?

可以使用 String 方法(如 LastIndexOfSubstring 查看以下代码以及此工作示例

string myText = "abc def ghi 123 abc def ghi 123 abc def";
string searchStr = "abc";
int lastIndex = myText.LastIndexOf(searchStr);
if(lastIndex>=0)
  myText = myText.Substring(0,lastIndex) + myText.Substring(lastIndex+searchStr.Length);
Console.WriteLine(myText);

请注意:如果您想用任何其他字符串替换abc,请在它们之间使用它,或者只是使用 String.Format 将它们连接起来,如下所示:

string replaceStr = "replaced";
string outputStr = String.Format("{0} {1}{2}",
                                 myText.Substring(0,lastIndex),
                                 replaceStr,
                                 myText.Substring(lastIndex+searchStr.Length));       

这是一个简单的问题,如何使用Remove方法

        string textToRemove = "abc";
        string myText = "abc def ghi 123 abc def ghi 123 abc def";
        myText = myText.Remove(myText.LastIndexOf(textToRemove), textToRemove.Length);
        Console.WriteLine(myText);

输出:abc def ghi 123 abc def ghi 123 def

如果要删除123 and def textToRemove.Length上仅+ 1之间的多余空格。

输出:abc def ghi 123 abc def ghi 123 def

C# - 替换某个字符串的第一个和最后一个出现

例:

string mystring = "123xyz123asd123rea";
在上面的字符串中,值 123

重复了三次,现在我们将看到如何将值"123"的第一次和最后一次出现替换为自定义值。

public static string ReplaceFirstOccurence(string originalValue, string occurenceValue, string newValue)
    {
        if (string.IsNullOrEmpty(originalValue))
            return string.Empty;
        if (string.IsNullOrEmpty(occurenceValue))
            return originalValue;
        if (string.IsNullOrEmpty(newValue))
            return originalValue;
        int startindex = originalValue.IndexOf(occurenceValue);
        return originalValue.Remove(startindex, occurenceValue.Length).Insert(startindex, newValue);
    }

    public static string ReplaceLastOccurence(string originalValue, string occurenceValue, string newValue)
    {
        if (string.IsNullOrEmpty(originalValue))
            return string.Empty;
        if (string.IsNullOrEmpty(occurenceValue))
            return originalValue;
        if (string.IsNullOrEmpty(newValue))
            return originalValue;
        int startindex = originalValue.LastIndexOf(occurenceValue);
        return originalValue.Remove(startindex, occurenceValue.Length).Insert(startindex, newValue);
    }

在上面的例子中,我们只是找到值的起始索引,删除这些值并插入新值。

希望对你有帮助...

我只想用空替换最后一个 abc。

你几乎拥有它,但正则表达式从左到右工作。如果你让解析器工作,从右到左,并处理任何正在进行的文本,它可以在正则表达式中完成。

string myText  = "abc def ghi 123 abc def ghi 123 abc def";
string pattern = "(abc)(.*?)$";
Regex.Replace(myText, pattern, "$2", RegexOptions.RightToLeft);

正则表达式替换返回字符串abc def ghi 123 abc def ghi 123 def

请注意,结果中有两个空格...您要求将ABC替换为"空";这就是它所做的。可以根据需要考虑空间问题

最新更新