JavaSE 成长之路程序员开源工具技巧

JavaSE基础(十四) - 正则表达式 & 常用API

2017-01-08  本文已影响170人  SawyerZh
Day14 - 常见对象(四)
  • 最近学习到第 23 天了,还有 4 天时间我的 JavaSE 课程就要结束了,之后会有一个考试,需要复习一下,正好利用这个时间把之前的学习内容给大家总结分享出来。

1.正则表达式

1.1 - 正则表达式的概述及简单使用

1.2 - 字符类

首先我们先来学习以下正则表达式中的字符类,我们想要对一个字符串中的各个字符进行判断,就要知道每个字符在正则表达式中的表示规则,知道了这个之后我们就能继续向下学习了。

Character classes
[abc] a, b, or c (simple class)
[^abc] Any character except a, b, or c (negation)
[a-zA-Z] a through z or A through Z, inclusive (range)
[a-d[m-p]] a through d, or m through p: [a-dm-p] (union)
[a-z&&[def]] d, e, or f (intersection)
[a-z&&[^bc]] a through z, except for b and c: [ad-z] (subtraction)
[a-z&&[^m-p]] a through z, and not m through p: [a-lq-z] (subtraction)

Reminder 💁‍♂️
[ ] 中括号中的内容我们可以理解为,对于一个单个的字符中,可以包含的字符的一个集合。

1.3 - 预定义字符类

预定义字符相当于正则表达式中,为我们提供了一些特殊的字符集合的快捷表达方式。学习了这个字符类之后,就可以用一个简单字符表达一个特殊的字符集合了。

redefined character classes
. Any character (may or may not match line terminators)
\d A digit: [0-9]
\D A non-digit: [^0-9]
\h A horizontal whitespace character:[ \t\xA0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000]
\H A non-horizontal whitespace character: [^\h]
\s A whitespace character: [ \t\n\x0B\f\r]
\S A non-whitespace character: [^\s]
\v A vertical whitespace character: [\n\x0B\f\r\x85\u2028\u2029]
\V A non-vertical whitespace character: [^\v]
\w A word character: [a-zA-Z_0-9]
\W A non-word character: [^\w]

1.4 - 数量词

上面我们学习了各种字符及字符集在正则表达式中的表达方式,但是如果我们想要表达一个字符出现多次时,我们就需要借助与正则表达式的另外一个规则了,这个规则就是数量词

quantifiers
X? X, once or not at all
X* X, zero or more times
X+ X, one or more times
X{n} X, exactly n times
X{n,} X, at least n times
X{n, m} X, at least n but not more than m times

1.5 - 分割功能

下面介绍一个 String 类中的方法,它的参数是 regex 也就是我们今天学习的正则表达式,那么我们来简单使用一下吧。

String str = "Sawyer,Jerry,Tom";
String[] arr_str = str.split("\\,”);
System.out.println(Arrays.toString(arr_str));

Reminder 💁‍♂️
这里的正则表达式需要写成 \\\, ,表示是正则表达式的 \\,
如果写成 \\, 则代表的是字符中的转义字符。

1.6 - 替换功能

String str1 = “I123 Love432 Sa324wyer!”;    // 去掉数字
// 任意数字,使用 + 可以匹配多位数字,减少 replace 次数,提高性能。
String reget = “\\d+”;
String str2 = str1.replaceAll(reget, “”);
System.out.println(str2);

1.7 - 分组功能

读读 API 📖
Capturing groups are numbered by counting their opening parentheses from left to right. In the expression ((A)(B(C))), for example, there are four such groups:
1 ((A)(B(C)))
2 (A)
3 (B(C))
4 (C)

/*
(.)代表任意一组字符
\\1 代表一组再次出现一次
\\2 代表第二组又出现了一次
*/
String regex1 = "(.)\\1(.)\\2";
System.out.println("快快乐乐".matches(regex1));  // true
System.out.println("快乐乐乐".matches(regex1));  // false
System.out.println("高高兴兴".matches(regex1));  // true
System.out.println("死啦死啦".matches(regex1));  // false
String regex2 = "(..)\\1";
System.out.println("死啦死啦".matches(regex2)); // true
System.out.println("高兴高兴".matches(regex2)); // true
System.out.println("快快乐乐".matches(regex2)); // false
String str_sou = "sdqqfgkkkhjppppk1";
// 将出现 1 次或多次的字符组切掉,+ 代表1组出现一次或多次。
String regex = "(.)\\1+";
String[] arr_str = str_sou.split(regex);
System.out.println(Arrays.toString(arr_str));
String str_sou = "我我....我...我.要...要要要...要学....学学..学.编..编编.编.程.程.程..程";
// 1.去掉.
String regex_replace1 = "\\.+";
String str_replace1 = str_sou.replaceAll(regex_replace1, "");
System.out.println(str_replace1);
// 2.替换组
String regex_replace2 = "(.)\\1+";
// $1 代表第一组中内容,()内的内容。
String str_replace2 = str_replace1.replaceAll(regex_replace2, "$1");
System.out.println(str_replace2); 

2.Pattern 和 Matcher

2.1 - Pattern 概述

读读 API 📖
A regular expression, specified as a string, must first be compiled into an instance of this class. The resulting pattern can then be used to create a Matcher object that can match arbitrary character sequences against the regular expression. All of the state involved in performing a match resides in the matcher, so many matchers can share the same pattern.

// 编译正则表达式
Pattern p = Pattern.compile("a*b");
// 获取匹配器
Matcher m = p.matcher("aaaaab");
// 执行匹配
boolean b = m.matches();

读读 API 📖
A matches method is defined by this class as a convenience for when a regular expression is used just once. This method compiles an expression and matches an input sequence against it in a single invocation. The statement
is equivalent to the three statements above, though for repeated matches it is less efficient since it does not allow the compiled pattern to be reused.

Instances of this class are immutable and are safe for use by multiple concurrent threads. Instances of the Matcher class are not safe for such use.

2.2 - Pattern 应用

String str_sou = "我的手机号是18676403416,曾经用过13364286497,还用过18988888888";

// 手机号的正则表达式
String REGEX_NUM = "1[3578]\\d{9}";

Pattern p = Pattern.compile(REGEX_NUM);

Matcher m = p.matcher(str_sou);

boolean b = m.find();   // 尝试查找与该匹配模式所匹配的下一个子序列

System.out.println(b);

// No match found 需要先执行 find() 后再获取
String str_group = m.group();   // 获取曾经查找到的子序列

System.out.println(str_group);

/*
* 正则匹配器的典型应用
* 遍历 find() 方法 获取所有 group() 子串
* */
while (m.find())
    System.out.println(m.group());

3.Math

The double value that is closer than any other to pi, the ratio of the circumference of a circle to its diameter.

13.0 -12
12.3 -12.99
12.0 -13

13.0 -12
12.3 -12.99
12.0 -13


4.Random

Random random1 = new Random();
for (int i = 0; i < 10; i++) {
    System.out.println(random1.nextInt());
}
Random random2 = new Random(1000);
int a = random2.nextInt();
int b = random2.nextInt();
System.out.println(a);
System.out.println(b);

取值范围 [0, bound) 等价于 [0, bound - 1]

👇 取值范围[0, 100) => [0, 99]
System.out.println(random1.nextInt(100));


5.System

5.1 - 概述

System 类包含几个有用的类字段和方法。它不能被实例化。

读读 API 📖
The System class contains several useful class fields and methods. It cannot be instantiated.

5.2 - 标准输入输出流。

1. In:标准输入流,默认指向键盘。
2. Out:标准输出流,默认指向控制台。

5.3 - 静态方法:

class FinalizeTest {
    // 当 FinalizeTest 类的对象变成垃圾对象后,回收器在不确定时间回收这个对象。
    // 在回收之前,会调用这个方法。
    @Override
    protected void finalize() throws Throwable {
        System.out.println("Garbage is cleared!");
    }
}

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
src - the source array.
srcPos - starting position in the source array.
dest - the destination array.
destPos - starting position in the destination data.
length - the number of array elements to be copied.


6.BigInteger

igInteger bi1 = new BigInteger("100");
BigInteger bi2 = new BigInteger("2");

System.out.println(bi1.add(bi2));       // +
System.out.println(bi1.subtract(bi2));  // -
System.out.println(bi1.multiply(bi2));  // *
System.out.println(bi1.divide(bi2));    // /

// 取商 取模
BigInteger[] arr_bi = bi1.divideAndRemainder(bi2);
System.out.println(Arrays.toString(arr_bi));

7.BigDecimal

BigDecimal bd1 = new BigDecimal(2.0);
BigDecimal bd2 = new BigDecimal(1.1);
System.out.println(bd1.subtract(bd2));    // 0.899999999999999911182158029987476766109466552734375
BigDecimal bd3 = new BigDecimal("2.0");
BigDecimal bd4 = new BigDecimal("1.1");
System.out.println(bd3.subtract(bd4));  // 0.9
BigDecimal bd5 = BigDecimal.valueOf(2.0);
BigDecimal bd6 = BigDecimal.valueOf(1.1);
System.out.println(bd5.subtract(bd6));  // 0.9

8.Date (java.util.Date)

8.1 - 概述

分配 Date 对象并初始化它自从标准基准时间,称为"新纪元",即 1970 年 1 月 1 日,格林尼治标准时间 00:00:00 代表指定的毫秒数。

读读 API 📖
Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

8.2 - 构造方法

8.3 - 成员方法

两个取值方式是相同的。
new Date().getTime()            // 通过事件对象获取毫秒值。
System.currentTimeMillis()  // 通过系统方法获取毫秒值。

9.SimpleDataFormat

// 方式一:默认格式
Date date = new Date();
SimpleDateFormat sdf1 = new SimpleDateFormat();
System.out.println(sdf1.format(date)); 

// 方式二:自定义格式
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date));
String str = "2016年12月22日 08:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date d = sdf.parse(str);    // 解析出 Date
System.out.println(sdf.format(d)); 

10.Test👨‍💻你来到这个世界多少天?

public class Test {
    public static void test() throws ParseException {
        // 1.将日期存储在 String 变量中
        String str_birthday = "1991 年 10 月 21 日";
        String str_today = "2016 年 11 月 22 日";

        // 2.定义日期格式化对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy 年 MM 月 dd 日");

        // 3.将日期字符串转换为日期对象
        Date date_birthday = sdf.parse(str_birthday);
        Date date_today = sdf.parse(str_today);

        // 4.通过日期对象计算毫秒值
        long time = date_today.getTime() - date_birthday.getTime();

        // 5.转换为天数
        System.out.println(time / 1000 / 60 / 60 / 24);
    }
}

11.Calendar

Reminder 💁‍♂️
月份:[0, 11]
星期:从周日开始。

Reminder 💁‍♂️
12 -> 0 年 进位 -> 2017


悄悄话 🌈


彩蛋 🐣


如果你觉得我的分享对你有帮助的话,请在下面👇随手点个喜欢 💖,你的肯定才是我最大的动力,感谢。

上一篇下一篇

猜你喜欢

热点阅读