在字符串中提取字符串的几个部分

Extract several parts of a string, inside a string

假设我有这个字符串:

/mytea/en/bt/aer?taxYear=2021&startMonth=1&endMonth=1

那里有三个参数:

如何从 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);
 }

它returns "1", 而 test = endMonth.

但是,如果我将 url 中的 endMonth 值更改为“10”,它仍然是 returns“1”,而不是 10。

使用String.split 方法根据分隔符拆分字符串。这需要几个步骤,但基本上你想做这样的事情:

import java.util.HashMap;

public class StringExtract {

    public static void main(String[] args) {
        String s = "/mytea/en/bt/aer?taxYear=2021&startMonth=1&endMonth=1";

        String[] a = s.split("\?");    // Split string around '?' character
        System.out.println(a[0] + "  " + a[1]);
        String[] b = a[1].split("&");   // Split string around '&' character

        HashMap<String, String> map = new HashMap<>();
        // For each name=value pair, split the string around '=' and print it out
        for(int i=0; i<b.length; i++) {
            String[] values = b[i].split("=");
            System.out.println("Name: " + values[0] + " Value: " + values[1]);
            map.put(values[0], values[1]); // store name/value pair in map
        }

        // Save values in variables
        int taxYear = Integer.parseInt(map.get("taxYear"));
        int startMonth = Integer.parseInt(map.get("startMonth"));
        int endMonth = Integer.parseInt(map.get("endMonth"));


    }
}

输出:

/mytea/en/bt/aer  taxYear=2021&startMonth=1&endMonth=1
Name: taxYear Values: 2021
Name: startMonth Values: 1
Name: endMonth Values: 1