Java 正则表达式 URL 解析



可能的重复项:
如何从给定的网址中提取参数

我正在尝试仅从此 url 中的参数中检索数字:

htt://tesing12/testds/fdsa?communityUuid=45352-32452-52

我试过这个没有运气:

^.*communityUuid=

任何帮助都会很好。

我建议不要使用简单的字符串操作路线。它更冗长,更容易出错。您也可以从内置类中获得一些帮助,然后利用您正在使用 URL(用"&"分隔的参数)的知识来指导您的实现:

String queryString = new URL("http://tesing12/testds/fdsa?communityUuid=45352-32452-52").getQuery();
String[] params = queryString.split("&");
String communityUuid = null;
for (String param : params) {
    if (param.startsWith("communityUuid=")) {
        communityUuid = param.substring(param.indexOf('=') + 1);
    }
}
if (communityUuid != null) {
    // do what you gotta do
}

这为您提供了检查 URL 格式良好性的好处,并避免了类似名称的参数可能引起的问题(字符串操作路由将报告"abc_communityUuid"和"communityUuid"的值)。

此代码的一个有用扩展是在迭代"参数"时构建映射,然后在映射中查询所需的任何参数名称。

我认为没有任何理由使用正则表达式。

我只会这样做:

String token = "communityUuid=";
String url = "htt://tesing12/testds/fdsa?communityUuid=45352-32452-52";
int index = url.indexOf(token) + token.length();
String theNumbers = url.substring(index);

注意:

您可能还必须查找下一个参数:

String token = "communityUuid=";
String url = "htt://tesing12/testds/fdsa?communityUuid=45352-32452-52";
int startIndex = url.indexOf(token) + token.length();
// here's where you might want to use a regex
String theNumbers = url.substring(startIndex).replaceAll("&.*$", "");

最新更新