到目前为止,我需要从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
任何帮助都将受到高度赞赏!感谢
答案 0 :(得分:6)
您正在使用matches()
来匹配整个字符串并定义2个捕获组。找到匹配项后,打印组1(这是第一个找到的UUID),然后打印第2组的内容,即第一个UUID 之后的其余字符串(用{{1}捕获) })。
您最好只匹配多次出现的UUID模式,而不匹配整个字符串。将(.*)
与更简单的Matcher.find
正则表达式
"\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12}"
请参阅Java demo输出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);
}
}
和058d2896-9a67-454c-95fc-8bec697d08c9
。