Regex用例,測試案例
在程式開發中會遇到需要匹配、尋找、替換、判斷字串的時候,這時使用Regex可以省下很多力氣。
自從jdk1.4推出java.util.regex包,就為我們提供了很好的JAVARegex應用平台。
下面列舉了部分用例
//尋找以Java開頭,任意結尾的字串
Pattern pattern = Pattern.compile("^hello.*")//^表示開頭.* 0個以上字元;
Matcher matcher = pattern.matcher("helloword");
System.out.print("\n" + matcher.matches());//返回布爾類型
//多條件分割字串
Pattern ptn=Pattern.compile("[?]");
String[] str=ptn.split("ab c?d .c");
for(int i=0;i<str.length;i++)
{
System.out.print( str[i]);
}
//文字替換(全部)
Pattern pattern = Pattern.compile("my");
Matcher matcher = pattern.matcher("my Hello World,my Hello World");
//替換第一個符合正則的資料
System.out.println(matcher.replaceAll("Java"));
//驗證是否為郵箱地址
String str="ceponline@yahoo.com.cn";
Pattern pattern = Pattern.compile("[//w//.//-]+@([//w//-]+//.)+[//w//-]+",Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.matches());
//去除html標記
Pattern pattern = Pattern.compile("<.+?>", Pattern.DOTALL);
Matcher matcher = pattern.matcher("<a href=/"index.html/">首頁</a>");
String string = matcher.replaceAll("");
System.out.println(string);
//尋找html中對應條件字串
Pattern pattern = Pattern.compile("href=/"(.+?)/"");
Matcher matcher = pattern.matcher("<a href=/"index.html/">首頁</a>");
if(matcher.find())
System.out.println(matcher.group(1));
}