Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从url提取字符串的正则表达式_Java_Regex - Fatal编程技术网

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

Java 从url提取字符串的正则表达式,java,regex,Java,Regex,我尝试的是从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/u

我尝试的是从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
i、 e结尾处没有a/号

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;
    }

有人能帮我吗?

您的正则表达式是这样编写的,它希望收到一个尾随的斜杠-这就是
(.*)
后面的斜杠的意思

您应该对此进行更改,以便它可以接受尾随斜杠或字符串的结尾<代码>(/|$)在这种情况下应该可以工作,这意味着您的正则表达式将是
[帐户]/(.*)(/|$)

  • [accounts]
    不尝试查找
    accounts
    单词,而是查找一个字符,该字符要么是
    a
    c
    (重复字符不会改变任何东西),
    o
    u
    n
    t
    或者
    s
    ,因为
    […]
    是。因此,摆脱那些
    [
    ]
    并用
    /
    替换它们,因为你最可能不想接受像
    /specialaccounts/
    这样的案例,而只想接受
    /accounts/

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

  • 如果您确定URL中只有一个
    /accounts/
    部分,您可以(并且为了获得更可读的代码,应该)将
    while
    更改为
    If
    甚至条件运算符。另外,不需要使用
    contains(“/accounts/”)
    ,因为它只是在整个字符串上添加了额外的遍历,这可以在
    find()
    中完成

  • 看起来您的方法没有使用类(任何字段)持有的任何数据,因此它可能是静态的

  • 演示:

    输出:

    u8m21ercgelj
    u8m21ercgelj
    u8m21ercgelj
    

    @ANP我想知道为什么您使用
    while
    而不是
    if
    。您是否假设URL中可以有多个
    /accounts/
    ?如果没有,则为避免混淆维护此代码的人员,应将其更改为
    If
    。但是,如果url可以有许多
    /accounts/
    ,那么发布的解决方案可能会失败,例如
    /accounts/accounts/foo
    (我可以尝试更正它,所以请告诉我是否需要更正)。很好的一点,我在回答中甚至没有查看
    [accounts]
    部分+1。大家好,我的URL中只有一个帐户。我会更正这个片段。谢谢大家
    u8m21ercgelj
    u8m21ercgelj
    u8m21ercgelj