java中正則表達式的使用


一、判斷字符串中是否含有某段字符串

Pattern.matches(String regex, String input)

示例

import java.util.regex.Pattern;

public class test {
     public static void main(String[] args) {
         String url = "www.baidu.com";
         String regex = "(.*)baidu(.*)";
         System.out.println(Pattern.matches(regex, url));
         //結果為true
     }
}

二、替換字符串的部分

replaceAll(String regex, String replacement)

示例

public class test {
     public static void main(String[] args) {
         
         String url = "www.baidu.com";

         String regex = "(\\w+)";
         String result2 = url.replaceAll(regex, "123");
         //結果為123.123.123
//如果想保留部分內容,那就用()表示那部分,替換部分用$表示 //如果有多個部分需要保留,那用多個$表示,並跟序號,表示第幾個 //示例 String regex2 = "www\\.(.*)\\.(.*)"; String result = url.replaceAll(regex2, "$1,$2"); //結果為baidu,com } }

三、找出字符串的所有符合條件的字符串

示例

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class test {
     public static void main(String[] args) {
         //找出百度網址中全部由小寫英文構成的字符串
        String url = "www.baidu.com";
        Pattern p = Pattern.compile("([a-z]+)");
        Matcher m = p.matcher(url);
        while (m.find()) {
            System.out.println(m.group());
            }
        /**
         * 結果
         * www
         * baidu
         * com
         * 
         */
     }
}

 


免責聲明!

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



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