正则表达式用例
在程序開發(fā)中會(huì)遇到需要匹配、查找、替換、判斷字符串的時(shí)候,這時(shí)使用正則表達(dá)式可以省下很多力氣。
自從jdk1.4推出java.util.regex包,就為我們提供了很好的JAVA正則表達(dá)式應(yīng)用平臺(tái)。
下面列舉了部分用例
//查找以Java開頭,任意結(jié)尾的字符串
Pattern pattern = Pattern.compile("^hello.*")//^表示開頭.* 0個(gè)以上字符;
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");
//替換第一個(gè)符合正則的數(shù)據(jù)
System.out.println(matcher.replaceAll("Java"));
//驗(yàn)證是否為郵箱地址
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標(biāo)記
Pattern pattern = Pattern.compile("<.+?>", Pattern.DOTALL);
Matcher matcher = pattern.matcher("<a href=/"index.html/">主頁</a>");
String string = matcher.replaceAll("");
System.out.println(string);
//查找html中對(duì)應(yīng)條件字符串
Pattern pattern = Pattern.compile("href=/"(.+?)/"");
Matcher matcher = pattern.matcher("<a href=/"index.html/">主頁</a>");
if(matcher.find())
System.out.println(matcher.group(1));
}
?
轉(zhuǎn)載于:https://www.cnblogs.com/Nick-li/p/6519956.html
總結(jié)
- 上一篇: thinkphp图片加载_标题栏ico展
- 下一篇: Linux性能优化之“关闭Ctrl+Al