【发布时间】:2022-01-18 20:39:48
【问题描述】:
假设我有这个字符串:
/mytea/en/bt/aer?taxYear=2021&startMonth=1&endMonth=1
这里有三个参数:
- taxYear : 4 位数 => 像“2021”
- startMonth : 1 位或 2 位 => 从 1 到 12
- endMonth:1 位或 2 位 => 从 1 到 12
如何从 Java 或 Scala 中的字符串中提取这些参数?
我已经试过了:
public static void main(String []args){
String hello = "/mytea/en/bt/aer?taxYear=2021&startMonth=1&endMonth=1";
String test = hello.substring(52, 53);
System.out.println(test);
}
它返回“1”,而 test = endMonth。
但是,如果我将 url 中 endMonth 的值更改为“10”,它仍然返回“1”,而不是 10。
【问题讨论】:
-
最简单的方法是使用
java.net.URL。 -
"但是,如果我将 url 中 endMonth 的值更改为“10”,它仍然返回“1”,而不是 10。” - 因为
hello.substring(52, 53)只解析出一个字符。解决这个问题的正确方法是在实际情况下使用indexOf:例如:hello.substring(X hello.indexOf("someSubstring")),或者使用hello.substring(52)一直到字符串的末尾。