您可以使用
(customers)\\/([^\\/\\s]+)|(branches)\\/([^\\/\\s]+)
或者简单地说
customers\\/([^\\/\\s]+)|branches\\/([^\\/\\s]+)
:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Solution {
public static void main(String[] args) {
final String regex = "(customers)\\/([^\\/\\s]+)|(branches)\\/([^\\/\\s]+)";
final String string = "http://localhost:8080/customer-api/customers/1128952/branches/83370\n"
+ "http://localhost:8080/customer-api/customers/1128952/branches/83370/validate";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Capture Group " + i + ": " + matcher.group(i));
}
}
}
}
印刷品
Capture Group 1: customers
Capture Group 2: 1128952
Capture Group 3: null
Capture Group 4: null
Capture Group 1: null
Capture Group 2: null
Capture Group 3: branches
Capture Group 4: 83370
Capture Group 1: customers
Capture Group 2: 1128952
Capture Group 3: null
Capture Group 4: null
Capture Group 1: null
Capture Group 2: null
Capture Group 3: branches
Capture Group 4: 83370
细节:
-
有四个捕获组,实际上你只需要其中的两个。(另外两个只是为了清楚起见)。
-
前两组是为客户准备的。
-
第三个和第四个是分支。
-
([^\\/\\s]+)
表示允许使用所有字符,但以下字符除外
\s
和
/
.