【问题标题】:Replacing width and height in url替换url中的宽度和高度
【发布时间】:2017-01-15 22:31:39
【问题描述】:

更改 w= number 和 h= number 的最简单方法是什么?

网址示例:

https://test.com/photos/226109/test-photo-226109.jpeg?w=1260&h=750&auto=compress&cs=tinysrgb&fit=crop

我必须动态更改粗体部分。

我可以像这样提取 w 的值:

  s = s.substring(s.indexOf("=") + 1, s.indexOf("&"));

但是我怎么能改变它呢? 我尝试搜索 Stackoverflow,但找不到任何东西。

谢谢。

【问题讨论】:

    标签: java string substring indexof


    【解决方案1】:

    如果我理解正确,您正在尝试替换 = 符号后的值,用于 hw

    您可以使用 RegEx 简单地做到这一点,如下所示:

    "https://test.com/photos/226109/test-photo-226109.jpeg?w=1260&h=750&auto=compress&cs=tinysrgb&fit=crop"
                            .replaceAll("w=\\d+", "w=NEW_VALUE").replaceAll("&h=\\d+", "&h=NEW_VALUE")
    

    上面发生的情况是,我们首先找到匹配w=AnyNumberHere 的模式,然后将整个部分替换为w=NEW_VALUE。同样,我们将&h=AnyNumberHere 替换为&h=NEW_VALUE

    此解决方案不依赖于长度,因此如果 URL 具有可变长度,它仍然可以工作,甚至在值 h=123w=1234 不存在时也可以工作;)

    【讨论】:

    • 谢谢。正是我想要的!
    • @core_m 很高兴我能帮上忙! :D。作为后续,我不知道 = 符号之后的数字长度是多少,所以我无法控制它。如果您知道长度,例如长度在 1 到 10 个字符之间)我们可以限制它!
    【解决方案2】:

    在您的情况下,您可以使用 String replaceAll 方法。使用示例:

    String string =
        "https://test.com/photos/226109/test-photo-226109." +
            "jpeg?w=1260&h=750&auto=compress&cs=tinysrgb&fit=crop";
    String replacedString = string
        .replaceAll(string.substring(string.indexOf("=") + 1, 
            string.indexOf("&")), "1000");
    

    【讨论】:

      【解决方案3】:

      当您从字符串中获取数字时,您可以将其转换为 StringBuffer。 像这样

      String s = new String("https://test.com/photos/226109/test-photo-226109.jpeg?w=1260&h=750&auto=compress&cs=tinysrgb&fit=crop");
      StringBuffer sb = new StringBuffer(s);
      sb.replace(s.indexOf("w=") + 2, s.indexOf("&"), "2000");
      sb.replace(s.indexOf("h=") + 2, s.indexOf("&"), "2000");
      s = sb.toString();
      

      【讨论】:

      • 如果 URL 是可变长度的,那么这将失败,它将替换 URL 的错误部分,从而破坏它。
      • 我的意思是 12 和 15 是 s.indexOf("=") + 1 的值
      • 您的代码仍然容易出错。例如,如果 url 不包含 = 它将出错,并且从第一个 = 符号替换到下一个 = 符号会损坏 url :S 在上面的示例中,它会使其看起来像: https://test.com/photos/226109/test-photo-226109.jpeg?w=2000750&auto=compress&cs=tinysrgb&fit=crop 删除 &h= 部分并将其后的值与替换值 2000 合并:S
      • 那更好,但如果 w=h= 由于某种原因不在 url 中,仍然会出错;) 尽管在 OP 提供的示例中,你的这些也有效
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 2017-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多