-------android培训、java培训、期待与您交流! ----------
package com.itcast.b25.reg;
import java.util.Arrays;
public class RegDemo1
{
/*
具体操作功能:
1,匹配:String matches方法。用规则匹配整个字符串,只要有一处不符合规则,就匹配结束,返回false。
2,切割:String split();
3,替换:String replaceAll(regex,str);如果regex中有定义组,可以在第二参数中通过$符号获取正则表达式中的已有的组。
*/
public static void main(String[] args)
{
/**
* 1.check qq by String operation method
对QQ号码进行校验
要求:5~15 0不能开头,只能是数字
这种方式,使用了String类中的方法,进行组合完成了需求。但是代码过于复杂。
*/
String qq = "1234567890";
//check_qq_1(qq);
/**
* 2.check qq by regular expression
*/
//check_qq_2(qq);
/**
* 3.匹配手机号
* 手机号段只有 13xxx 15xxx 18xxxx
*/
String str = "13521198691";
String regex = "1[358]\\d{9}";
//match(str, regex);
/**
* 4.匹配0-多次
*/
str = "a111g";
regex = "[\\w&&[^_]]\\d*"; //"[a-zA-Z]\\d*"
//match(str, regex);
/**
* 5.split
*/
str = "w1, w3.w4 w5 w6";
regex = "[,\\.\\s]+";
str = "c:\\abc\\a.txt";
regex = "\\\\";
//repeat
str = "erkktyqqquizzzzzo";
regex = "(\\w)\\1+"; //"(.)\\1+"
regex = "(.)\\1+"; //.是太极,是上帝,相当于Object
//split(str, regex);
/**
* 6.replace
*/
str = "wer1389980000ty1234564uiod234345675f";
String replacement = "#";
regex = "\\d+"; //greedy: wer#ty#uiod#f
//regex = "\\d+?";// not greedy: wer##########ty#######uiod#########f
str = "erkktyqqquizzzzzo"; // remove the repeated characters;
regex = "(.)\\1+";
replacement = "$1";
replace(str, regex, replacement);
}
private static void replace(String str, String regex, String replacement)
{
String str2 = str.replaceAll(regex, replacement);
System.out.println(str2);
}
private static void split(String str, String regex)
{
String[] arr = str.split(regex);
System.out.println(arr.length);
System.out.println(Arrays.toString(arr));
}
private static void match(String str, String regex)
{
if(str.matches(regex))
System.out.println("OK");
else
System.out.println("Err");
}
private static void check_qq_2(String qq)
{
String regex = "[^0]\\d{4,14}"; //[1-9]\\d{4,14}
if(qq.matches(regex))
{
System.out.println("OK");
}
else
{
System.out.println("Error");
}
}
private static void check_qq_1(String qq)
{
int len = qq.length();
if(len>4 && len<16)
{
if(!qq.startsWith("0"))
{
try
{
int i = Integer.parseInt(qq);
System.out.println("OK");
}
catch(NumberFormatException e) //this is runtime exception
{
System.out.println("格式不正确");
}
}
else
{
System.out.println("can not start with 0");
}
}
else
{
System.out.println("长度不对");
}
}
}
package com.itcast.b25.reg;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegDemo2
{
/**
* 正则表达式的第四个功能。
4,获取:将字符串中的符合规则的子串取出。
操作步骤:
1,将正则表达式封装成对象。
2,让正则对象和要操作的字符串相关联。
3,关联后,获取正则匹配引擎。
4,通过引擎对符合规则的子串进行操作,比如取出。
*/
public static void main(String[] args)
{
String str = "ming tian jiu yao fang jia le ,da jia。 再加些中文。";
String regex = "\\b[a-zA-Z]+\\b";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while(matcher.find())
{
System.out.println(matcher.group());
System.out.println(matcher.start()+"->"+matcher.end());
}
}
}
-------android培训、java培训、期待与您交流! ----------