Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

uri

I need to extract the UUID from a URI and 50% successful so far, can someone please be kind enough to suggest to me the exact matching regex for this ??

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

The output i'm currently getting is

058d2896-9a67-454c-95fc-8bec697d08c9 ===========> A
/documents/058d2896-9a67-454c-9aac-8bec697d08c9 ===========> B

Now i want the output from the B to be just

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

any help would be highly appreciated!!! Thanks

like image 715
Infamous Avatar asked Sep 21 '16 08:09

Infamous


1 Answers

You are using matches() to match the entire string and define 2 capturing groups. After you found the match, you print Group 1 (that is the first found UUID) and then the contents of Group 2 that is the rest of the string after the first UUID (captured with (.*)).

You'd better just match multiple occurrences of the UUID pattern, without matching the entire string. Use Matcher.find with a simpler "\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12}" regex:

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

See Java demo outputting 058d2896-9a67-454c-95fc-8bec697d08c9 and 058d2896-9a67-454c-9aac-8bec697d08c9.

like image 140
Wiktor Stribiżew Avatar answered Sep 24 '22 00:09

Wiktor Stribiżew