几个简单的Java正则用例
字符串验证
//查找以Java开头,任意结尾的字符串
Pattern pattern1 = Pattern.compile("^Java.*");
Matcher matcher = pattern1.matcher("Java你好");
//当条件满足时,将返回true,否则返回false
boolean b = matcher.matches();
System.out.println(b);
输出:true
多条件分割字符串
Pattern pattern2 = Pattern.compile("[,!. ]+");
String str[] = pattern2.split("hello Java! hello,yang zheng.");
for (String string : str) {
System.out.println(string);
}
输出:
hello
Java
hello
yang
zheng
文字替换
//文字替换(首次出现字符)
Pattern pattern3 = Pattern.compile("[^a-z]");
Matcher matcher3 = pattern3.matcher("hello@yang$zheng%hello*java~!");
//将非字母的字符替换成空格
System.out.println(matcher3.replaceAll(" "));//replaceFirst替换第一个
输出:hello yang zheng hello java
Pattern pattern4 = Pattern.compile("[^a-z]");
Matcher matcher4 = pattern4.matcher("hello@yang$zheng%hello*java~!");
StringBuffer sbr = new StringBuffer();
while (matcher4.find()) {
matcher4.appendReplacement(sbr, "?");
}
matcher4.appendTail(sbr);
System.out.println(sbr.toString());
输出:hello?yang?zheng?hello?java??
验证是否为邮箱地址
String str5="ceponline@yahoo.com.cn";
Pattern pattern5 = Pattern.compile("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+",Pattern.CASE_INSENSITIVE);
Matcher matcher5 = pattern5.matcher(str5);
System.out.println(matcher5.matches());
去除html标记
Pattern pattern6 = Pattern.compile("<.+?>", Pattern.DOTALL);
Matcher matcher6 = pattern6.matcher("<a href=\"index.html\">主页</a>");
String str6 = matcher6.replaceAll("");
System.out.println(str6);
查找html中对应条件字符串
Pattern pattern7 = Pattern.compile("href=\"(.+?)\"");
Matcher matcher7 = pattern7.matcher("<a href=\"index.html\">主页</a>");
if(matcher.find())
System.out.println(matcher.group(1));
截取http://地址
//截取url
Pattern pattern8 = Pattern.compile("(http://|https://){1}[\\w\\.\\-/:]+");
Matcher matcher8 = pattern8.matcher("dsdsds<http://dsds//gfgffdfd>fdf");
StringBuffer buffer = new StringBuffer();
while(matcher.find()){
buffer.append(matcher.group());
buffer.append("\r\n");
System.out.println(buffer.toString());
}
替换指定{}中文字
String str9 = "Java目前的发展史是由{0}年-{1}年";
String[][] object={new String[]{"\\{0\\}","1995"},new String[]{"\\{1\\}","2007"}};
System.out.println(replace(str9,object));
public static String replace(final String sourceString, Object[][] object) {
// TODO Auto-generated method stub
String temp=sourceString;
for(int i=0;i<object.length;i++){
String[] result=(String[])object[i];
Pattern pattern = Pattern.compile(result[0]);
Matcher matcher = pattern.matcher(temp);
temp=matcher.replaceAll(result[1]);
}
return temp;
}