【问题标题】:Replace second occurence of ? with an &替换第二次出现的 ?与 &
【发布时间】:2014-05-08 16:13:32
【问题描述】:

谁能提供适当的代码来仅替换“?”的第二个实例在带有“&”的字符串中?

我环顾四周,但似乎无法完成,而且我对正则表达式不太感兴趣。

谢谢

【问题讨论】:

  • 只使用 IndexOf 并在第二次出现时替换
  • 如果这是用于查询字符串解析,可能有更好的方法。
  • 反过来呢?只写 & 然后将第一个替换为 ?
  • @RononDex - 如果字符串中有 3 个或更多 ? 怎么办?
  • 告诉编写流程的人来修复他的代码

标签: c# regex


【解决方案1】:

您可以使用IndexOf指定起始索引来查找第二个问号的索引,然后使用Substring

var index = input.IndexOf('?', input.IndexOf('?') + 1);
var ouput = string.Concat(input.Substring(0,index), "&", input.Substring(index + 1));

或者:

var output = new string(input.Select((c, i) => i == index ? '&' : c).ToArray());

你也可以写一个扩展方法:

public static string ReplaceWith(
        this string source, 
        char charToReplace,
        int index)
{
    if(source == null) throw new ArgumentNullException("source");

    if (index == -1) return source;

    var output = new char[source.Length];

    for (int i = 0; i < source.Length; i++)
    {
        if (i != index) output[i] = source[i];

        else output[i] = charToReplace;

    }
    return new string(output);
}

然后使用它:

var index = input.IndexOf('?', input.IndexOf('?') + 1);
var output = input.ReplaceWith('&', index);

【讨论】:

  • 此输出可能有误(或可能引发异常),因为有时可能只有一个问号或没有问号
  • @LoganMurphy - 不是根据 OP 的问题,但绝对值得注意。
  • @LoganMurphy 在第一个解决方案中,你是对的,可以通过简单的检查来修复 if(index != -1) 但如果没有问号或一个问号,第二个只会返回相同的字符串
  • @Selman22 这就是我实际上可能会这样做的方式,对于这样一个简单的用例,没有太多需要使用正则表达式。 +1
【解决方案2】:

最简单的Regex大概是:

var regex = new Regex(@"(\?.*?)\?");
var test = "asdf?a=5?b=6&c=2";
test = regex.Replace(test, @"$1&"); // asdf?a=5&b=6&c=2

var test2 = "asdf?a=5?b=6?c=2";
test2 = regex.Replace(test, @"$1&"); // asdf?a=5&b=6?c=2

它将用&amp; 替换第二个?,但如果存在,则不会替换第三个/第四个/等。

【讨论】:

    【解决方案3】:

    替换:

    (.*?\?.*?)(\?)(.*)
    

    如果您想使用正则表达式,请使用 $1&amp;$3

    【讨论】:

    • 他们想替换?与 & 所以它可能是$1&amp;$3?
    【解决方案4】:

    这是一种处理Replace 重载的方法。

    var regex = new Regex(@"(^.*?\?.*?)(\?)");
    var r = regex.Replace("asdf ? fdas ? jkl ?", m => m.Groups[1] + "&", 1).Dump();
    // asdf ? fdas & jkl ?
    

    【讨论】:

      【解决方案5】:

      请参考下面的示例,其中我从给定字符串中删除了第二次和第三次出现的$

      string s = "like for example $  you don't have $  network $  access";       
      Regex rgx = new Regex("\\$\\s+");
      s = Regex.Replace(s, @"(\$\s+.*?)\$\s+", "$1$$"); 
      

      【讨论】:

      • 这是如何回答问题的?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      • 2022-10-07
      • 2016-03-20
      • 2019-04-19
      • 2020-07-10
      • 2016-04-02
      相关资源
      最近更新 更多