2016-09-21 171 views
2

我需要從URI中提取UUID,並且目前爲止50%成功,有人請向我建議完全匹配的正則表達式嗎?如何使用Java正則表達式從URI中提取UUID

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 

任何幫助,將不勝感激!謝謝

回答

4

您正在使用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

+1

它的工作和感謝良好的解釋..乾杯! – Infamous