Java util 包学习笔记一
1. Random, Observable
Random:
- 实现接口:Serializable
- 子类:SecureRandom
- 若使用相同的 seed 生成实例且调用方法顺序相同,则返回相同的数。
- 构造函数接受一个 long 参数。
- 无类方法,使用一系列 next**() 方法生成伪随机数。
nextGaussian()返回 0-1 之间的高斯正态分布 double 数。
2. regex 包
Pattern:
- 正则表达式的编译表现形式。
static Pattern compile(String regex):创建静态工厂方法。static Pattern compile(String regex, int flags):flags 包括 CASE_INSENSITIVE, MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ。split(CharSequence input):根据正则切割字符串。split(CharSequence input, int limit):限制匹配次数。
Matcher:
- 通过
pattern.matcher(CharSequence)生成。 - 三种匹配方式:
matches():匹配整个字符串。lookingAt():匹配从开头开始的子串。find([int start]):查找多重模式匹配,类似迭代器。
- 组的概念:第零组为整个式子,后续括号内为分组。
start()和end():返回匹配位置的起始下标和结束下标加 1。- 替换方法:
replaceAll,replaceFirst,appendReplacement。
示例代码:
import java.util.regex.*;
class Groups {
static public final String poem = "Twas brillig,and the slithy toves ";
public static void main(String[] args) {
Matcher m = Pattern.compile("(?m)(\S+)/s+((\S+)/s+(\S+))$").matcher(poem);
(m.find()){
( i=; i<=m.groupCount(); i++) {
System.out.print( + m.group(i) + );
}
System.out.println();
}
}
}

