- 【懒惰量词】在量词后面加
?
,如nickName=(.*?
)
public static void main(String[] args) {
String a = "https://www.xxx.com?nickName=汉武帝&";
Pattern pattern = Pattern.compile("nickName=(.*?)(&|$)");
Matcher matcher = pattern.matcher(a);
if (matcher.find()) {
for (int i = 0; i <= matcher.groupCount(); i++) {
System.out.println("--------------");
System.out.println(matcher.group(i));
}
}
}
- 【分组命名】在左括号后跟
?<名称>
,如nickName=(?<nickName>
.*?)
public static void main(String[] args) {
String a = "https://www.xxx.com?nickName=汉武帝&";
Pattern pattern = Pattern.compile("nickName=(?<nickName>.*?)(&|$)");
Matcher matcher = pattern.matcher(a); // testURL
if (matcher.find()) {
System.out.println(matcher.group("nickName"));
}
}