Regex用例,測試案例

來源:互聯網
上載者:User

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));
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.