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

How to extract the UUID's from the URI using Java regex

我需要从 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

任何帮助将不胜感激!!!谢谢

您正在使用 matches() 匹配整个字符串并定义 2 个捕获组。找到匹配项后,打印组 1(即第一个找到的 UUID),然后打印组 2 的内容,即 第一个 UUID 之后的其余字符串(用 (.*)).

您最好只匹配多次出现的 UUID 模式,而不匹配整个字符串。使用 Matcher.find 和更简单的 "\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 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 demo 输出 058d2896-9a67-454c-95fc-8bec697d08c9058d2896-9a67-454c-9aac-8bec697d08c9