0

我有一条路/departments/{dept}/employees/{id}。我如何获取deptid从路径/departments/{dept}/employees/{id}

例如,我想获得dept1id1如果路径是/departments/dept1/employees/id1

我试过了

String pattern1 = "departments/"
String pattern2 = "/employees"
Pattern p = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2));
Matcher m = p.matcher(text);
while (m.find()) {
   String a = m.group(1);
}

有没有更简单的方法来获取 dept1 和 id1?我宁愿不使用 string.split,因为我有不同的路径要获取路径参数,并且我不希望依赖于路径参数的索引位置。

4

3 回答 3

2

使用 Spring... 或:

String url = /departments/{dept}/employees/{id}
             /----none--/-dept-/---none---/-id-

对 url 进行拆分,得到数组 1 和 3 的位置:

String urlSplited = url.split("/");
String dept = urlSplited[1];
String id = urlSplited[3];
于 2019-08-30T19:28:51.417 回答
0

如果您正在使用Spring framework,那么您可以使用一个专门用于此目的的类AntPathMatcher并使用它的方法extractUriTemplateVariables

因此,您可以拥有以下内容:

AntPathMatcher matcher = new AntPathMatcher();

String url = "/departments/dept1/employees/id1";
String pattern = "/departments/{dept}/employees/{id}";

System.out.println(matcher.match(pattern, url));
System.out.println(matcher.extractUriTemplateVariables(pattern, url).get("dept"));
System.out.println(matcher.extractUriTemplateVariables(pattern, url).get("id"));
于 2019-08-30T20:51:33.500 回答
0

如果您更喜欢正则表达式:

import org.junit.Test;
import java.util.regex.Pattern;

        public class ExampleUnitTest {

        @Test
        public void test_method() throws Exception {

            Pattern digital_group = Pattern.compile("[//]");

            CharSequence line = "test/message/one/thing";

            String[] re = digital_group.split(line);

            for (int i=0;i<re.length;i++) {

                System.out.println(re[i]);

            }

        } 

    } //END: class ExampleUnitTest

输出是:

test
message
one
thing

Process finished with exit code 0
于 2019-08-30T19:57:26.887 回答