Java常用類(三):正則表達式;Pattern類和Matcher類;Math類;Random類;System類;BigDecimal類

Java常用類(三)

一、正則表達式

1、概述

	正則表達式:即正確規則的表達式,是指一個用來描述或者匹配一系列符合某個句法規則的字符串的單個字符串。其實就是
一種規則。有自己特殊的應用。

2、常用規則字符

	規則字符在java.util.regex Pattern類中
A:字符
	x 字符 x。舉例:'a'表示字符a
	\\ 反斜線字符。
	\n 新行(換行)符 ('\u000A') 
	\r 回車符 ('\u000D')
B:字符類
	[abc] a、b 或 c(簡單類) 
	[^abc] 任何字符,除了 a、b 或 c(否定) 
	[a-zA-Z] a到 z 或 A到 Z,兩頭的字母包括在內(範圍) 
	[0-9] 0到9的字符都包括
C:預定義字符類
	. 任何字符 (注意:如果要使用'.'本身,則要使用轉義字符:"\.")
	\d 數字:[0-9]
	\w 單詞字符:[a-zA-Z_0-9]
		在正則表達式裏面組成單詞的東西必須有這些東西組成
D:邊界匹配器
	^ 行的開頭 
	$ 行的結尾 
	\b 單詞邊界
E:Greedy 數量詞 
	X? X,一次或一次也沒有 比如""空串 就是沒有
	X* X,零次或多次  大於等於1次 都算多次
	X+ X,一次或多次
	X{n} X,恰好 n 次 
	X{n,} X,至少 n 次 
	X{n,m} X,至少 n 次,但是不超過 m 次 

3、正則表達式的判斷

	String類的功能:public boolean matches(String regex)

示例:

import java.util.Scanner;

public class BLog {
    public static void main(String[] args) {
        /*
            需求:校驗鍵盤錄入的qq號碼:
		    1:要求必須是5-11位數字
		    2:0不能開頭
	    */
        Scanner scanner = new Scanner(System.in);
        System.out.println("請輸入QQ號:");
        String qqStr = scanner.nextLine();
        boolean f=checkQQ(qqStr);
        if(f){
            System.out.println("QQ號碼格式正確!");
        }else {
            System.out.println("QQ號碼格式錯誤!");
        }
    }

    private static boolean checkQQ(String qqStr) {
        //第一位爲1到9數字,第二位之後爲0到9數字,長度4到10位,總共5到15位
        String regexStr="[1-9][0-9]{4,10}";
        return qqStr.matches(regexStr);
    }
}

4、正則表達式分割功能

String類的功能:public String[] split(String regex)

示例:

import java.util.Arrays;

public class Blog1 {
    public static void main(String[] args) {
        /*需求:有如下一個字符串:"91absad27ssdaf46safasf38safs50",拿出其中的數字,並排序,拼串
         請寫代碼實現最終輸出結果是:"27 38 46 50 91"  */
        String oldStr="91aASd27ssNJf46sSQasf38safs50";
        String newStr=getNewStr(oldStr);
        System.out.println(newStr);
    }

    private static String getNewStr(String oldStr) {
        String regexSplitStr="[a-zA-z]+";//定義分割符正則表達式
        String[] split = oldStr.split(regexSplitStr);//使用分割符正則表達式分割字符串

        int[] arr=new int[split.length];//定義int[]類型數組存儲分割出來的數字

        for (int i = 0; i < split.length; i++) {
            arr[i]=Integer.parseInt(split[i]);//遍歷存儲數字
        }
        Arrays.sort(arr);//排序
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            sb.append(arr[i]).append(" ");//拼串
        }
        return sb.toString().trim();//將StringBuilder類型轉換爲String類型,並去除最後的空格
    }
}
運行結果:
27 38 46 50 91

Process finished with exit code 0

5、正則表達式替換功能

String類的功能:public String replaceAll(String regex,String replacement)

示例:

public class Blog2 {
    public static void main(String[] args) {
        /*
        *   需求:將"ss5455sd5a45sda56566SD5FSD65SD5F4__5645_sdf5565"字符串中除了數字之外的內容刪除
        *   思路:將除數字之外的內容替換爲空串:  ""
        */
        String str="ss5455sd5a45sda56566SD5FSD65SD5F4__5645_sdf5565";
        String newStr=getNewStr(str);
        System.out.println(newStr);
    }

    private static String getNewStr(String str) {
        String  regexReplaceStr="[a-zA-Z_]+";//定義要替換字符串的正則表達式
        return str.replaceAll(regexReplaceStr,"");//替換字符串(刪除)
    }
}
運行結果:
5455545565665655456455565

Process finished with exit code 0

二、Pattern類和Matcher類

	 Pattern模式器,用來封裝一個正則表達式
     Matcher匹配器,可以封裝一個待匹配的數據,可以通過匹配器中的方法,進行匹配

示例:

		//獲取一個模式器
        Pattern p = Pattern.compile("a*b*");
        //通過模式器獲取一個匹配器
        Matcher m = p.matcher("aaaaab");
        //進行匹配
        boolean b = m.matches();
        System.out.println(b);//true
	Matcher匹配器的方法:
		boolean find ()
        嘗試查找與該模式匹配的輸入序列的下一個子序列。
        String group ()
        返回由以前匹配操作所匹配的輸入子序列。

舉例:

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

public class Blog3 {
    public static void main(String[] args) {
        //把下面這個字符串中是三個字母組成的單詞,獲取出來
        // da jia ting wo shuo, jin tian yao xia yu, bu shang wan zi xi, gao xing bu?

        String str="da jia ting wo shuo, jin tian yao xia yu, bu shang wan zi xi, gao xing bu?";

        //定義三個字母單詞的正則表達式 注意加單詞邊界,否則是三個字符的都會取到
        String strRegx="\\b[a-z]{3}\\b";
        //把正則表達式封裝到模式器中
        Pattern p = Pattern.compile(strRegx);
        //獲取匹配器,把待匹配的字符串傳進去
        Matcher matcher = p.matcher(str);
        while (matcher.find()){ //判斷下一個字符詞組是否爲三個字母組成的單詞
            String group = matcher.group();//獲取匹配上的單詞
            System.out.println(group.concat(" "));
        }
    }
}
運行結果:
jia jin yao xia wan gao 
Process finished with exit code 0

三、Math類概述和方法使用

A:Math類概述
	Math 類包含用於執行基本數學運算的方法,如初等指數、對數、平方根和三角函數。 
B: 成員變量
	public static final double E : 		自然底數
	public static final double PI:		圓周率
C:成員方法
	public static int abs(int a)		取絕對值
	public static double ceil(double a)	 向上取整
	public static double floor(double a)	向下取整
	public static int max(int a,int b)      獲取最大值
	public static int min(int a, int b)	 獲取最小值
	public static double pow(double a,double b) 獲取a的b次冪
	public static double random() 獲取隨機數返回帶正號的 double 值,該值大於等於 0.0 且小於 1.0public static int round(float a)  四捨五入
	public static double sqrt(double a) 獲取正平方根

演示:

public class MathDemo {
    public static void main(String[] args) {
        //Math 數學工具類
        //屬性
        double pi = Math.PI;
        double e = Math.E;
        //方法
        double num = Math.random(); //生成double類型隨機數 0-----1 之間
        //獲取最值
        int max = Math.max(19, 20);//20
        int min = Math.min(20, 40);//20
        //向上取整,向下取整
        double ceil = Math.ceil(1.9);//2.0
        double floor = Math.floor(1.9);//1.0
        //四捨五入
        long round = Math.round(1.48);//小數點後一位四捨五入 結果:1
        //求一個數的幾次冪
        double pow = Math.pow(2, 3);//2的3次方
        //求平方根
        double sqrt = Math.sqrt(4);//2.0
        //求一個數的立方根
        double pow2 = Math.pow(8, 1.0/3);//2.0
        //求一個數的絕對值
        int abs = Math.abs(-1);//1
    }
}

四、Random類

A:Random類的概述
	此類的實例用於生成僞隨機數流,使用48位的種子,如果用相同的種子創建兩個 Random 實例,
	則對每個實例進行相同的方法調用序列,它們將生成並返回相同的數字序列。
B:構造方法
	public Random()			 沒有給定種子,使用的是默認的(當前系統的毫秒值)
	public Random(long seed)		 給定一個long類型的種子,給定以後每一次生成的隨機數是相同的
C:成員方法
	public int nextInt()//沒有參數 表示的隨機數範圍 是int類型的範圍
	public int nextInt(int n)//可以指定一個隨機數範圍 
	void nextBytes(byte[] bytes)  生成隨機字節並將其置於用戶提供的空的 byte 數組中。 

示例:

public class RandomDemo {
    public static void main(String[] args) {
        //生成隨機數據的類
        // 此類的實例用於生成僞隨機數流。此類使用 48 位的種子,
        Random random = new Random();
        //生成一些隨機整數
        random.nextInt(); //如果沒有傳入一個範圍,生成的隨機數就是int的範圍
        random.nextInt(100); //範圍是0-99,包含0和99

        random.nextDouble();//生成一個隨機double範圍內的數
        random.nextBoolean();//生成一個隨機boolean值
        byte[] bytes= new byte[10];
        //隨機一些byte範圍的數,填到這個數組中
        random.nextBytes(bytes);
        show();
        show();
        show();
    }

    public static void show() {
        int[] arr=new int[10];
        //Random( long seed)
        //使用單個 long 種子創建一個新的隨機數生成器。
        //給定了種子,每次生成的隨機數都是一樣的
        Random random = new Random(1);
        for (int i = 0; i < 10; i++) {
            int i1 = random.nextInt(10);
            arr[i]=i1;
        }
        System.out.println(Arrays.toString(arr));
    }
}
運行結果:
[5, 8, 7, 3, 4, 4, 4, 6, 8, 8]
[5, 8, 7, 3, 4, 4, 4, 6, 8, 8]
[5, 8, 7, 3, 4, 4, 4, 6, 8, 8]

Process finished with exit code 0

五、System類

A:System類的概述
	System 類包含一些有用的類字段和方法。它不能被實例化。
成員變量:in(標準的輸入流,對應設備是鍵盤)
		out(標準的輸出流,對應的設備是屏幕) 
B:成員方法
	public static void gc()//調用垃圾回收器
	public static void exit(int status)//退出java虛擬機 0 爲正常退出 非0爲 異常退出
	public static long currentTimeMillis()//獲取當前時間的毫秒值

示例:

import java.io.PrintStream;
import java.util.Scanner;

public class Blog5 {
    public static void main(String[] args) {
        //InputStream 抽象類
        //in
        //public static final InputStream in“標準”輸入流。此流已打開並準備提供輸入數據。通常,此流對應於鍵盤輸入
        Scanner sc= new Scanner(System.in);
        //out
        //public static final PrintStream out“標準”輸出流。此流已打開並準備接受輸出數據。通常,此流對應於顯示器輸出
        PrintStream out = System.out;
        out.println("abc");

        System.gc();//運行垃圾回收器

        //獲取當前系統的毫秒值
        //計算機元年 1970-01-01 00:00:00-------當前時刻(毫秒值)
        long start = System.currentTimeMillis();
        System.out.println(start+"(毫秒)");
        //退出JVM
        System.exit(0);//給0正常退出 ,非0強制退出
    }
}

六、BigDecimal類

A:BigDecimal的概述
	由於在運算的時候,float類型和double很容易丟失精度,
	所以,爲了能精確的表示、計算浮點數,Java提供了BigDecimal
	不可變的、任意精度的有符號十進制數。
B:構造方法
	public BigDecimal(String val)
C:成員方法
	public BigDecimal add(BigDecimal augend)//加
	public BigDecimal subtract(BigDecimal subtrahend)//減
	public BigDecimal multiply(BigDecimal multiplicand)//乘
	public BigDecimal divide(BigDecimal divisor)//除法
	public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode)//scale 小數點後面保留幾位
	// roundingMode 取捨模式 比如四捨五入

示例:

public class MyTest {
    public static void main(String[] args) {
        double a=1.999999;
        double b=3.111111;
        //如果對精度要求比較高,就可以使用 BigDecimal
        BigDecimal aNum = new BigDecimal(a);
        BigDecimal bNum = new BigDecimal(b);
        BigDecimal add = aNum.add(bNum); //加
        System.out.println(add);
        BigDecimal subtract = aNum.subtract(bNum); //減
        System.out.println(subtract);

        BigDecimal multiply = aNum.multiply(bNum);
        System.out.println(multiply); //乘
        //不能整除時,我們要規定,保留位數,以及取捨方式
        BigDecimal divide = aNum.divide(bNum,30,BigDecimal.ROUND_CEILING);//除
        System.out.println(divide);
        System.out.println(1==0.999999999999999999999);//true
    }
}
運行結果:
5.1111100000000002641087348820292390882968902587890625
-1.1111120000000000995754589894204400479793548583984375
6.222218888889000619624654277117785066535292925651337156290189393803569117835650104098021984100341796875
0.642856844387744431287794403143
true

Process finished with exit code 0

七、BigInteger類

概述:可以讓超過Integer範圍內的數據進行運算

構造方法
public BigInteger(String val)
成員方法
public BigInteger add(BigInteger val)
public BigInteger subtract(BigInteger val)
public BigInteger multiply(BigInteger val)
public BigInteger divide(BigInteger val)
public BigInteger[] divideAndRemainder(BigInteger val)

示例:

import java.math.BigInteger;

public class MyTest1 {
    public static void main(String[] args) {
        BigInteger bi1=new BigInteger("99999999999999999999999999");
        BigInteger bi2=new BigInteger("77777777777777777777");

        System.out.println(bi1.add(bi2));   //加
        System.out.println(bi1.subtract(bi2));   //減
        System.out.println(bi1.multiply(bi2));   //乘
        System.out.println(bi1.divide(bi2));    //除
        System.out.println("----------------");
        BigInteger[] arr=bi1.divideAndRemainder(bi2);    //取除數和餘數
        System.out.println("數組長度:"+arr.length);
        for(int i=0;i<arr.length;i++){
            System.out.println(arr[i]);
        }
    }
}
運行結果:
100000077777777777777777776
99999922222222222222222222
7777777777777777777699999922222222222222222223
1285714
----------------
數組長度:2
1285714
22222222222223222221

Process finished with exit code 0
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章