【问题标题】:Replace after a string - Before a character在字符串之后替换 - 在字符之前
【发布时间】:2015-12-08 18:37:27
【问题描述】:

我有一个类似的字符串:

string str = "First Option: This is a text. This is second text.";

我可以将This is a text. 替换为:

str = str.Replace("This is a text.", "New text");

但是我的常量词是First Option:This is a text 不是常量,所以如何替换First Option: 之后的文本直到出现.(这意味着在This is second text. 之前)。 在这个例子中,预期的结果是:

First Option: New text. This is second text.

【问题讨论】:

  • 要么使用String.IndexOf 获取索引并使用字符串长度来计算要替换的字符串的位置,要么查看正则表达式(regex)。
  • 改用Regex.Replace

标签: c# replace


【解决方案1】:

一种选择是改用Regex.Replace

str = Regex.Replace(str, @"(?<=First Option:)[^.]*", "New text");

(?&lt;=First Option:)[^.]* 匹配除点'.' 之外的零个或多个字符序列,前面是First Option: 通过positive look-behind

【讨论】:

    【解决方案2】:

    不是最短的,但如果你想避免使用正则表达式:

    string replacement = "New Text";
    string s = "First Option: This is a text.This is second text.";
    string[] parts = s.Split('.');
    parts[0] = "First Option: " + replacement;
    s = string.Join(".", parts);
    

    【讨论】:

      【解决方案3】:

      查找.IndexOf()Substring(...)。这将为您提供所需的:

      const string findText = "First Option: ";
      var replaceText = "New Text.";
      var str = "First Option: This is a text. This is second text.".Replace(findText, "");
      var newStr = findText + str.Replace(str.Substring(0, str.IndexOf(".") + 1), replaceText);
      
      Console.WriteLine(newStr);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-19
        • 2021-09-24
        • 1970-01-01
        • 2023-04-05
        • 2012-09-04
        • 1970-01-01
        • 2012-06-25
        • 2020-08-26
        相关资源
        最近更新 更多