从URL中提取字符串的正则表达式

4
我正在尝试从URL中提取我的账户ID以进行其他验证。以下是我的URL示例:
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;
    }

有人可以帮我吗?

2个回答

4
  1. [accounts] 不是在查找 accounts 这个单词,而是查找一个字符,这个字符是 ac(重复的字符不会改变结果)、ount 或者 s 中的一个,因为 [...] 是一个字符类。所以要去掉那些 [],用 / 替换它们,因为你很可能不想接受像 /specialaccounts/ 这样的情况,只想匹配 /accounts/

  2. 看起来你只想在 /accounts/ 后面找到下一个非 / 的部分。在这种情况下,你可以直接使用 /accounts/([^/]+)

  3. 如果你确定 URL 中只会有一个 /accounts/ 部分,你可以(也应该)将你的 while 改为 if 或甚至三目运算符。而且没有必要使用 contains("/accounts/"),因为它只会在整个字符串上额外遍历一次,这可以在 find() 中完成。

  4. 看起来你的方法没有使用类中持有的任何数据(任何字段),所以它可以是静态的。

演示:

//we should resuse once compiled regex, there is no point in compiling it many times
private static Pattern pattern = Pattern.compile("/accounts/([^/]+)");
public static String extractAccountIdFromURL(String url) {
    Matcher matcher = pattern.matcher(url);
    return matcher.find() ? matcher.group(1) : null;
}

public static void main(java.lang.String[] args) throws Exception {
    String examples = 
            "http://localhost:8024/accounts/u8m21ercgelj/\r\n" + 
            "http://localhost:8024/accounts/u8m21ercgelj\r\n" + 
            "http://localhost:8024/accounts/u8m21ercgelj/users?";
    for (String url : examples.split("\\R")){// split on line separator like `\r\n`
        System.out.println(extractAccountIdFromURL(url));
    }
}

输出:

u8m21ercgelj
u8m21ercgelj
u8m21ercgelj

@ANP,我想知道为什么你使用 while 而不是 if。你是否假设 URL 中可能会有多个 /accounts/?如果不是,那么为了不让维护此代码的人感到困惑,你应该将其更改为 if。但是,如果 URL 可以有多个 /accounts/,那么发布的解决方案可能会在像 /accounts/accounts/foo 这样的情况下失败(如果需要纠正,请告诉我)。 - Pshemo
好的,我在回答中甚至没有注意到[accounts]部分。对于这个答案给个+1。 - Daniel Bernsons
大家好,我的URL中只会有一个帐户。我会纠正代码片段。谢谢所有人。 - Anoop M Nair

3

你的正则表达式写成了期望接收一个斜线 - 这就是 (.*?) 后面的斜线的含义。

你应该修改它,以便它可以接受斜线或字符串的结尾。在这种情况下,(/|$) 应该可以工作,意味着你的正则表达式应该是 [accounts]/(.*?)(/|$)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接