我正在尝试从URL中提取我的账户ID以进行其他验证。以下是我的URL示例:
我需要提取 url 中的 u8m21ercgelj。我尝试了下面的代码,但对于结尾没有 / 的情况,如
http://localhost:8024/accounts/u8m21ercgelj/
http://localhost:8024/accounts/u8m21ercgelj
http://localhost:8024/accounts/u8m21ercgelj/users?
我需要提取 url 中的 u8m21ercgelj。我尝试了下面的代码,但对于结尾没有 / 的情况,如
http://localhost:8024/accounts/u8m21ercgelj
,它会失败。public String extractAccountIdFromURL(String url) {
String accountId = null;
if ( url.contains("accounts")) {
Pattern pattern = Pattern.compile("[accounts]/(.*?)/");
Matcher matcher = pattern.matcher(url);
while (matcher.find()) {
accountId = matcher.group(1);
}
}
return accountId;
}
有人可以帮我吗?
while
而不是if
。你是否假设 URL 中可能会有多个/accounts/
?如果不是,那么为了不让维护此代码的人感到困惑,你应该将其更改为if
。但是,如果 URL 可以有多个/accounts/
,那么发布的解决方案可能会在像/accounts/accounts/foo
这样的情况下失败(如果需要纠正,请告诉我)。 - Pshemo[accounts]
部分。对于这个答案给个+1。 - Daniel Bernsons