如何使用Java正则表达式从URI中提取UUID?

6

我需要从URI中提取UUID,目前的成功率为50%,请有人能够友善地建议给我一个确切匹配的正则表达式吗?

public static final String SWAGGER_BASE_UUID_REGEX = ".*?(\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12})(.*)?";

public static final String abc="https://127.0.0.1:9443/api/am/store/v0.10/apis/058d2896-9a67-454c-95fc-8bec697d08c9/documents/058d2896-9a67-454c-9aac-8bec697d08c9";
public static void main(String[] args) {
    Pattern pairRegex = Pattern.compile(SWAGGER_BASE_UUID_REGEX);
    Matcher matcher = pairRegex.matcher(abc);

    if (matcher.matches()) {
        String a = matcher.group(1);
        String b = matcher.group(2);
        System.out.println(a+ " ===========> A" );
        System.out.println(b+ " ===========> B" );
    }
}

我目前得到的输出是:
058d2896-9a67-454c-95fc-8bec697d08c9 ===========> A
/documents/058d2896-9a67-454c-9aac-8bec697d08c9 ===========> B

现在我希望B的输出只是:

058d2896-9a67-454c-9aac-8bec697d08c9

任何帮助都将不胜感激!!!谢谢
1个回答

12

你正在使用matches()来匹配整个字符串并定义两个捕获组。当你找到匹配时,你打印出第一个找到的UUID(即第一组)然后是第二组内容,即第一个UUID之后的其余字符串(使用(.*)进行捕获)。

最好只匹配多个UUID模式而不是整个字符串。使用简单的"\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12}"正则表达式和Matcher.find方法:

public static final String abc="https://127.0.0.1:9443/api/am/store/v0.10/apis/058d2896-9a67-454c-95fc-8bec697d08c9/documents/058d2896-9a67-454c-9aac-8bec697d08c9";
public static final String SWAGGER_BASE_UUID_REGEX = "\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12}";

public static void main (String[] args) throws java.lang.Exception
{
    Pattern pairRegex = Pattern.compile(SWAGGER_BASE_UUID_REGEX);
    Matcher matcher = pairRegex.matcher(abc);
    while (matcher.find()) {
        String a = matcher.group(0);
        System.out.println(a);
    }
}

请查看Java演示输出058d2896-9a67-454c-95fc-8bec697d08c9058d2896-9a67-454c-9aac-8bec697d08c9


2
差不多六年过去了,我回到了自己的问题。猜猜!它仍然有效 <3 - Infamous

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