您的位置:首页 > 其它

正规表达式的使用

2016-03-14 15:06 211 查看
正则表达式的使用是为了过滤掉不想显示的内容,从而产生的一种过滤规则。

/**
* (一)
*  \d: [0-9]
*  \w: [a-zA-Z0-9]
*  \s: 一个空白字符:回车 换行 tab 空格
*  . : 表示任意字符
*
*  (二)
*  \D: 非数字
*  \W: 非单词字符
*  \S: 非空白
*
*  (三)
*  {n,m} n表示最少次数,最多次数
*  {n} 表示一定的次数
*  {,m} 最多m次
*  {n,} 最少n次
*
*  (四)
*  转义:对于匹配语法字符需要转义
*  . 表示任意字符,使用 \. 匹配“点”
*  . 表示任意字符,使用 \. 匹配“点”
*  \ 是转义字符,使用 \\ 匹配 "\"
*
*/


原始的正则过滤方式

public static void fun1(){
System.out.println("");
System.out.println(">>>>>>>>>> fun1 <<<<<<");
String speak = "那些年真的我了个去,我去,我草啊!";
String rule = "(我[去草])|(我了个去)";
System.out.println("过滤后>>>>> "+speak.replaceAll(rule, "**"));
}


2.按照类型和个数模糊匹配

public static void fun2(){
System.out.println("");
System.out.println(">>>>>>>>>>> fun2 <<<<<<<<<<");
String t = "0,4|0,3|0,5|1,4";
String[] data = t.split("\\|");// \|
System.out.println("data:"+Arrays.toString(data));

Cell[] cells = new Cell[4]; // new 一个Cell数组
int i=0;
for(String s: data){
String[] ss = s.split(",");  //  遍历后截取, 获得第一个0 4 第二个 0 3 ....
//          System.out.println(Arrays.toString(ss));
//          System.out.println("##>> "+ss[0]+"....."+ss[1]);

int row = Integer.parseInt(ss[0]);
int col = Integer.parseInt(ss[1]);
Cell cell = new Cell(row, col);  // 强转new出cell类型 让如到刚刚new的cell[] 数组中
cells[i++] = cell;
}
System.out.println("cells:"+Arrays.toString(cells));  // 输出
}


Example:检查一个String是否符合规定

public static void fun3(){
System.out.println("");
System.out.println(">>>>>>>>>>>> fun3 <<<<<<<<<<<<");
String str = "0,4|0,3|0,5|1,4";
String rule = "^(\\d,\\d\\|){3}\\d,\\d$"; // | 为何要使用\\|
System.out.println(str.matches(rule));
}


忽略(Ignore)大小写比较字符串相等

public static void fun4(){
String rule = "Bye";
while(true){
Scanner userIn = new Scanner(System.in);
String input = userIn.next();
System.out.println("你输入的是: "+input);
if(rule.equalsIgnoreCase(input)){
System.out.println("输入的意思是: 再见");
}else{
System.err.println("无法匹配翻译,请重新输入");
}
}
}


4.匹配手机号码

public static void fun5(){
String rule = "^\\d{11}$";
while(true){
Scanner sc = new Scanner(System.in);
String input = sc.next();
System.out.println("你输入的是: "+input);
if(input.matches(rule)){
System.out.println("是一个手机号码:>> "+input);
}else{
System.err.println(input+" 不是一个手机号码,请重新输入! ");
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  正则表达式