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

时间:2017-06-30 00:14:16

标签: java regex

我正在尝试从网址中提取我的帐户ID以进行其他验证。 看我的网址样本。

http://localhost:8024/accounts/u8m21ercgelj/
http://localhost:8024/accounts/u8m21ercgelj
http://localhost:8024/accounts/u8m21ercgelj/users?

我需要的是从网址中提取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 个答案:

答案 0 :(得分:4)

你的正则表达式是这样编写的,它希望收到一个斜杠 - 这是(.*?)之后斜杠的含义。

您应该更改它,以便它可以接受尾部斜杠或字符串的结尾。 (/|$)应该适用于这种情况,这意味着您的正则表达式将是[accounts]/(.*?)(/|$)

答案 1 :(得分:3)

  1. [accounts]不会尝试查找accounts字,但是一个字符ac(字符的重复不会改变任何内容) ),ounts因为[...]character class。因此,请删除[],并将其替换为/,因为您很可能不希望接受/specialaccounts/但仅/accounts/这样的情况。

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

  3. 如果您确定网址中只有一个/accounts/部分,您可以(以及更易读的代码)将您的while更改为if甚至是有条件的运营商。此外,不需要contains("/accounts/"),因为它只是在整个字符串上添加了额外的遍历,这可以在find()中完成。

  4. 您的方法看起来并不是使用您的类(任何字段)所持有的任何数据,因此它可能是静态的。

  5. 演示:

    //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
    
相关问题