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

7、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
发布了55 篇原创文章 · 获赞 23 · 访问量 4357

猜你喜欢

转载自blog.csdn.net/y_Engineer/article/details/96201942