1. 校验
/**
* 校验 email
* @param email
* @return
*/
public static boolean validateEmail(String email){
String regex = "([a-z\\d]+[_|\\-|\\.]?)*[a-z\\d]+@(([a-z\\d]+[\\-]?)*[a-z\\d]+\\.)+[a-z]{2,3}";
Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(email);
return m.matches();
}
2. 分割
String data = "orchids,chrysanthemum;narcissus,lotus";
String[] flowers = data.split(",|;");
for (String flower : flowers){
System.out.println(flower);
}
3. 替换
String data = "<head><title>登录</title></head>";
// 使用 reluctant 模式由小到大进行匹配
data = data.replaceAll("<.+?>", ""); // 登录
4. 提取
String data = "<a href=\"http://www.apache.org/\">Apache</a>";
String regex = "(http://|https://){1}[\\w\\.:/\\-]+";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(data);
if (m.find()){
System.out.println(m.group()); // http://www.apache.org/
}
5. 三种匹配模式
String text = "A1BB23CCC456DDDD78910_";
Pattern p = null;
Matcher m = null;
int start, end;
// greedy 贪婪模式
System.out.println("===== greedy =====");
p = Pattern.compile("(\\w+)\\d+_?");
m = p.matcher(text);
while (m.find()){
start = m.start();
end = m.end();
System.out.println(text.substring(start, end));
System.out.println("group 1 : " + m.group(1));
}
// Reluctant 勉强模式
System.out.println("===== reluctant =====");
p = Pattern.compile("(\\w+?)\\d+_?");
m = p.matcher(text);
while (m.find()){
start = m.start();
end = m.end();
System.out.println(text.substring(start, end));
System.out.println("group 1 : " + m.group(1));
}
// Possessive 占有模式
System.out.println("===== possessive =====");
p = Pattern.compile("(\\w++)\\d+_?");
m = p.matcher(text);
while (m.find()){
start = m.start();
end = m.end();
System.out.println(text.substring(start, end));
System.out.println("group 1 : " + m.group(1));
}
// output
===== greedy =====
A1BB23CCC456DDDD78910_
group 1 : A1BB23CCC456DDDD7891
===== reluctant =====
A1
group 1 : A
BB23
group 1 : BB
CCC456
group 1 : CCC
DDDD78910_
group 1 : DDDD
===== possessive =====
6. END