Regular
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regularj {
/* 2017-02-16 13:16:05
* matches 判断是否匹配指定的正则表达式
* replaceAll 将一个字符串替换为指定的值
* replacefirst 将字符串中第一个匹配的 指定的子串替换成
*
* 预定义字符
* . 匹配任何字符
* \d 匹配 0-9
* \D 非数字
* \s 匹配所有的空白字符,包括空格、制表符、回车符、换页符、换行符
* \S 匹配所有非空白字符
* \w 匹配所有的单词字符 包括0-9 26个字母 下划线
* \W 匹配非单词的字符
*
* digit 数字
* space 空格
* word 单词
*
* 枚举 [asdf] asdf 中的任意一个
* 范围 - a-c a到c 中的任意字符
* 否 ^ [^asd] 不是asd
* 与 && 求交集 [a-d && [bc]] 表示bc
* 并 [a-d[m-p]] == [a-dm-p]
*
*
* 边界匹配符
* ^ 行的开头
* $ 行的结尾
* \b 单词的边界
* \B 非单词的边界
* \A 输入的开头
* \G 前一个匹配的结束
* \Z 输入的结尾、仅用于最后的结束符
* \z 输入的结尾
*
* greedy 贪婪模式 数量表示符默认采用贪婪模式 除非另有表示,否则 直到无法匹配为止
*
* reluctant 勉强模式 用问号后缀 ? 表示 只会匹配最少的字符,也称为最小匹配模式
* possessive 占有模式 + 表示
*
*
* 使用正则表达式
* Pattern 和matcher 对象
*
* Pattern 对象是正则表达式编译后在内存中的表示形式,因此正则表达式字符串必须先被编译为pattern 对象 。
* 然后再利用pattern对象创建对应的matcher对象
* 执行匹配所涉及的状态保留在matcher对象中
* 多个matcher 对象可共享同一个pattern对象
*
*/
public static void main(String[] args) {
// 正则表达式
String string = "string,string,string";
System.out.println(string.replaceFirst("\\w*", "-")); // 贪婪模式 -,string,string
System.out.println(string.replaceFirst("\\w?", "-")); // 勉强模式 -tring,string,string
// matcherj();
// matcherfindj();
}
/* 2017-02-16 14:19:41
*
*/
private static void matcherfindj() {
String string2 = "13012345678" + "asd" + "12345678123" + "asd" + "45812345678" +"asd" + "130123456789";
Pattern pattern = Pattern.compile("((13\\d)|(12\\d))\\d{8}"); //匹配 13 或者12 开头 后面面8位
Matcher matcher = pattern.matcher(string2);
while (matcher.find()) {
//find方法依次查找字符串中与pattern匹配的子串,一旦找到,下次调用将接着向下找
//还可以传入int 参数 从int 位置开始查找
System.out.println(matcher.group());
}
}
/* 2017-02-16 14:08:07
*
*/
private static void matcherj() {
Pattern pattern = Pattern.compile("asd"); // 将一个字符串编译成pattern对象
Matcher matcher = pattern.matcher("aaaaaaaa"); // 使用pattern对象创建matcher对象
boolean b = matcher.matches();
boolean b2 = Pattern.matches("asd", "aaaa"); //如果pattern对象只使用一次,可以用pattern 的matches 静态方法
//patt 是不可变类,可供多个并发线程安全使用
//matcher 的常用方法
// matcher.find()
// matcher.group()
// matcher.start()
// matcher.end()
// matcher.lookingAt()
// matcher.matches()
// matcher.reset(input)
//charsequence 接口,该接口代表一个字符序列
//charbuffer string StringBuffer StringBuilder 都是它的实现类, CharSequence 代表一个各种表示形式的字符串
}
}
还没有评论,来说两句吧...