Pattern类:
例子:
- Pattern pattern =Pattern.compile("[,\\s]+");
- String[] result = pattern.split("onetwo three,four,five, six");
- for(int i = 0; i<result.length; i++){
- System.out.println(result[i]);
- }
输出结果是:
one
two
three
four
five
six
Pattern类的静态方法compile用来编译正则表达式,在此[,\\s]+表示若干个","或者若干个空格匹配
split方法使用正则匹配将字符串切割成各子串并且返回
Matcher类:
注意,Matcher的获得是通过Pattern.matcher(CharSequencecharSequence);输入必须是实现了CharSequence接口的类
常用方法:
matches()判断整个输入串是否匹配,整个匹配则返回true
例如下面会输出true
String str1 = "hello";
Pattern pattern1 =Pattern.compile("hello");
Matcher matcher1 =pattern1.matcher(str1);
System.out.println(matcher1.matches());
lookingAt()从头开始寻找,找到匹配则返回true
例如下面会输出true
String str2 = "hello yangfan!";
Pattern pattern2 =Pattern.compile("hello");
Matcher matcher2 =pattern2.matcher(str2);
System.out.println(matcher2.lookingAt());
find()扫描输入串,寻找下一个匹配子串,存在则返回true
例如下面将会将所有no替换成yes
Pattern pattern =Pattern.compile("no");
Matcher matcher =pattern.matcher("Does jianyue love yangfan? no;" +
"Does jianyue love yangfan? no;Does jianyue love yangfan? no;");
StringBuffer sb = new StringBuffer();
boolean find = matcher.find();
while(find){
matcher.appendReplacement(sb, "yes");
find = matcher.find();
}
matcher.appendTail(sb);
System.out.println(sb.toString());