java正則表達式


正則表達式是很常見的。但是也是很容易出錯的。
  所以,整理了寫 Java正則表達式的方法。
 
1、正則初體驗:pattern(模式)。split(分割_成數組)。compile(編譯)、matcher(匹配器)
//  獲取需要正則的主體
  String str2 = "ceponline@yahoo.com.cn";
//  創建模型Pattern,再編寫compile正則表達式語法
  Pattern pattern5 = Pattern.compile(".+@.+\\..+?");
//  使用正則模型去匹配matcher需要正則的主體
  Matcher matcher5 = pattern5.matcher(str2);
//  打印驗證正則是否正確
System.out.print("\n" + matcher5.matches());       
 
2、正則表達式語法:(在compile中的字符串)
  .+ 表示任何不為空的    \\.  表示轉譯為 .              ^開頭       $結尾 
  ? 表示為懶惰模式。匹配到第一個滿足的就停止               * :0到無窮          + :1到無窮                
  \d 數字:[0-9]       \D 非數字:[^0-9]      \w數字和字母[a-zA-Z0-9]      \W 非數字和字母  [^a-zA-Z0-9]
  • 在一些語言里,"\\"的意思是"在正則表達式里插入一個反斜杠。"但是在Java里,"\\"的意思是"要插入一個正則表達式 的反斜杠,
  • 那么java正則表達式就應該是"\\w+"。如果要插入一個反斜杠,那就得用"\\\\"。
  • java像換行,跳格之類的只用一根反斜杠"\n\t"。
 
3、正則實戰:
Pattern pattern = Pattern.compile("[, |]+");
String[] strs = pattern.split("Java Hello World Java,Hello,,World|Sun");
for (int i = 0; i < strs.length; i++) {
    System.out.print("\t" + strs[i]);
}
輸出結果 為: Java      Hello     World     Java     Hello     World     Sun
 
驗證郵箱地址:
String str2 = "ceponline@yahoo.com.cn";
Pattern pattern5 = Pattern.compile(".+@.+\\..+?");
Matcher matcher5 = pattern5.matcher(str2);
System.out.print("\n" + matcher5.matches());             //返回 布爾值
 
去除html標記:
Pattern pattern6 = Pattern.compile("<.+?>");
Matcher matcher6 = pattern6.matcher("<a href=\"index.html\">主頁</a>");
String string = matcher6.replaceAll("");
System.out.println("\r" + string);                 
 
// 截取url
Pattern pattern8 = Pattern.compile("<http://.+?>");
Matcher matcher8 = pattern8.matcher("dsdsds<http://www.baidu.com/>fdf");
if (matcher8.find()) {
System.out.println(matcher8.group());                   // 返回匹配的字符串
}
 
簡單的 example:
String str = "正則表達式 Hello World,正則表達式 Hello World ";
str.replace("hello" , "我要替換hello")
 
篩選數字
    public Double regexGetMath(String matcher) {
        Pattern pattern = Pattern.compile("[^0-9/.]");
        Matcher match = pattern.matcher(matcher);
        String getStr = match.replaceAll("");
        Double getNum = Double.parseDouble(getStr);
        return getNum;
    }
 
篩選字符串
      public String regexGetLetterLow(String matcher) {
        Pattern pattern = Pattern.compile("[^a-zA-Z]");
        Matcher match = pattern.matcher(matcher);
        String getStr = match.replaceAll("").toLowerCase();
        return getStr;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM