如果不是非常复杂的正则,往往使用我们的String类完成。
以下都是普通方法
方法名称:
public boolean matches(String regex):正则验证,使用指定的字符串判断其是否符合给出的正则表达式结构
public String replaceAll(String regex,String replacement):全部替换
public String replaceFirst(String regex,String replacement):替换首个
public String[] split(String regex):全部拆分
publicString[] split(String regex.int limit):部分拆分
给出的几个方法里面对于替换和拆分上实际难度不高,最关键的就是正则匹配,在验证上特别多.
范例:字符串替换:
public static void main(String[] args) throws Exception{
String str="12klasjdlkasdaks&……*3";
String regex="[^a-z]";
//这里要实现将所有的不是小写字母的用空字串替换,只留小写字母
System.out.println(str.replaceAll(regex, ""));
}

范例:字符串拆分
public static void main(String[] args) throws Exception{
String str="12klasjdlkasdaks3333kjasdkads555";
//这里要实现按照数字拆
String regex="\\d+";
String result[]=str.split(regex);
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}

正则最大的惊喜是验证功能。
范例:验证一个字符串是否是数字,如果是将其变为double型。
数字有可能是整数(10)也可能是小数(10.2)
public static void main(String[] args) throws Exception{
String str="10.2";
String regex="\\d+(\\.\\d+)?";
System.out.println(str.matches(regex));
if(str.matches(regex)){
System.out.println(Double.parseDouble(str));//转型前进行验证
}
}
范例:判断给定的字符串是否是一个IP地址(IPV4)
public static void main(String[] args) throws Exception{
String str="192.168.1.1";
String regex="\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
System.out.println(str.matches(regex));
}
范例:给定一个字符串,要求判断是否是日期格式,如果是就转化为Date格式。
public static void main(String[] args) throws Exception{
String str="2009-03-23";
String regex="\\d{4}-\\d{2}-\\d{2}";
System.out.println(str.matches(regex));
if(str.matches(regex)){
Date date=new SimpleDateFormat("yyyy-MM-dd").parse(str);
System.out.println(date);
}
}
范例:判断电话号码(自己查吧)
范例:验证email地址
以上是几个典型的数据验证操作,以后接触到类似验证的时候,一定要求掌握相关正则。
网友评论