在 url 中替换宽度和高度
Replacing width and height in url
更改 w= number 和 h= number 的最简单方法是什么?
url的例子:
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("&"));
但是我怎么能改变它呢?
我尝试搜索 Whosebug,但找不到任何东西。
谢谢。
在您的情况下,您可以使用 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();
如果我理解正确,您正试图替换 =
符号后的值 h
和 w
。
您可以简单地使用 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=123
或 w=1234
也有效不存在 ;)
更改 w= number 和 h= number 的最简单方法是什么?
url的例子:
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("&"));
但是我怎么能改变它呢? 我尝试搜索 Whosebug,但找不到任何东西。
谢谢。
在您的情况下,您可以使用 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();
如果我理解正确,您正试图替换 =
符号后的值 h
和 w
。
您可以简单地使用 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=123
或 w=1234
也有效不存在 ;)