String email = "star@163.com";
Pattern p = compile("(\\w+)[@]{1}(\\w+[.]\\w+)");
Matcher m = p.matcher(email);
if (m.find()) {
for (int i = 0; i <= m.groupCount(); i++) {
System.out.println(String.format("分组:%d,捕获:%s",i,m.group(i)));
}
}
#结果#:
分组:0,捕获:star@163.com
分组:1,捕获:star
分组:2,捕获:163.com
p = compile("(\\d+)(0*)");
m = p.matcher("500");
if (m.find()) {
for (int i = 1; i <= m.groupCount(); i++) {
System.out.println(String.format("分组:%d,捕获:%s",i,m.group(i)));
}
}
#结果#:
分组:1,捕获:500
分组:2,捕获:
p = compile("(\\d+?)(0*)");
m = p.matcher("1000");
if (m.find()) {
for (int i = 1; i <= m.groupCount(); i++) {
System.out.println(String.format("分组:%d,捕获:%s",i,m.group(i)));
}
}
#结果#:
分组:1,捕获:1
分组:2,捕获:000
p = compile("([a-z])([A-Z])(\\1)(\\2)");
m = p.matcher("sAsA");
if (m.find()) {
for (int i = 1; i <= m.groupCount(); i++) {
System.out.println(String.format("分组:%d,捕获:%s",i,m.group(i)));
}
}
System.out.println("aa".matches("([aB])\\1"));
System.out.println("BB".matches("([aB])\\1"));
#结果#:
分组:1,捕获:s
分组:2,捕获:A
分组:3,捕获:s
分组:4,捕获:A
true
true
System.out.println("updateUser".replaceAll("([a-z])([A-Z])","$1_$2").toLowerCase());
System.out.println("update_user".replaceAll("_(\\D)","$1"));
#结果#:
update_user
updateuser
p = compile("([¥$])(\\d+)(?:[.])(?:\\d+)");
m = p.matcher("¥128.85");
if (m.find()) {
for (int i = 1; i <= m.groupCount(); i++) {
System.out.println(String.format("分组:%d,捕获:%s",i,m.group(i)));
}
}
#结果#:
分组:1,捕获:¥
分组:2,捕获:128
p = compile("([a-z]{4})(?=520)");
m = p.matcher("Gstar520-moon520");
while (m.find()) {
for (int i = 1; i <= m.groupCount(); i++) {
System.out.println(String.format("分组:%d,捕获:%s",i,m.group(i)));
}
}
#结果#:
分组:1,捕获:star
分组:1,捕获:moon
p = compile("([a-z]{4})(?!520)");
m = p.matcher("Gstar520-moon520-love1989");
while (m.find()) {
for (int i = 1; i <= m.groupCount(); i++) {
System.out.println(String.format("分组:%d,捕获:%s",i,m.group(i)));
}
}
#结果#:
分组:1,捕获:love
p = compile("(?<=520)([a-z]{4})");
m = p.matcher("Gstar520moon520love1989");
while (m.find()) {
for (int i = 1; i <= m.groupCount(); i++) {
System.out.println(String.format("分组:%d,捕获:%s",i,m.group(i)));
}
}
#结果#:
分组:1,捕获:moon
分组:1,捕获:love
p = compile("(?<!520)([a-z]{4})");
m = p.matcher("gstar520moon520love1989");
while (m.find()) {
for (int i = 1; i <= m.groupCount(); i++) {
System.out.println(String.format("分组:%d,捕获:%s",i,m.group(i)));
}
}
#结果#:
分组:1,捕获:gsta
转载请注明原文地址:https://ipadbbs.8miu.com/read-53874.html