繁体   English   中英

替换网址中的宽度和高度

[英]Replacing width and height in url

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

网址示例:

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,但找不到任何东西。

谢谢。

如果我正确理解,您正在尝试将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不存在,甚至可以使用;)

您可以使用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");

从字符串中获取数字时,可以将其转换为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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM