先来看看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) | 普通 | 全部拆分 |
public String[] split(String regex,int limit) | 普通 | 部分拆分 |
例:
//输出小写字母
public class Nice {
public static void main(String args[]) {
String str = "sdfAFUsfi[sf*sfSDwr*sYD" ;
String regex = "[^a-z]" ; //此处编写正则
System.out.println(str.replaceAll(regex,"")) ;
}
}
//用数字拆分
public class Nice {
public static void main(String args[]) {
String str = "sdf34AFU67sf789i[sf*s90-=fSDw345r*sYD" ;
String regex = "\\d+" ; //[0-9]此处编写正则
String result[] = str.split(regex) ;
for (int x=0 ; x < result.length ; x++) {
System.out.println(result[x]) ;
}
}
}
//验证字符串是否是数字,如果是则变为double型
public class Nice {
public static void main(String args[]) {
String str = "100.01" ;
String regex = "\\d+(\\.\\d+)?" ;
System.out.println(str.matches(regex)) ;
if (str.matches(regex)) { //转型之前进行验证
System.out.println(Double.parseDouble(str)) ;
}
}
}
//判断ipv4
public class Nice {
public static void main(String args[]) {
String str = "192.168.1.1" ;
String regex = "(\\d{1,3}\\.){3}\\d{1,3}" ; //由于有重复,所以进行了简化
System.out.println(str.matches(regex)) ;
}
}
//判断是否为日期格式,如果是则转换为Date型数据
import java.text.SimpleDateFormat ;
import java.util.Date ;
public class Nice {
public static void main(String args[]) throws Exception{
String str = "2111-11-11" ; //无法判断日期的有效性
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) ;
}
}
}
//输出电话号码
//(010)-12345678或者010-12345678或者12345678
import java.text.SimpleDateFormat ;
import java.util.Date ;
public class Nice {
public static void main(String args[]) throws Exception{
String str = "(010)-12345678" ;
String regex = "((\\d{3,4}-)|(\\(\\d{3,4}\\)-))?\\d{7,8}" ; //为了解决括号的问题,才会有那么多转义
System.out.println(str.matches(regex)) ;
}
}
//email的判断,给@前面设置字数范围与结尾字符范围,后缀设置限制
public class Nice {
public static void main(String args[]) throws Exception{
String str = "nihao_Nice123@nice.com.cn" ;
String regex = "[a-zA-Z][a-zA-Z0-9_\\.]{0,28}[a-zA-Z0-9]@\\w+\\.(net|cn|com\\.cn|net\\.cn|org|gov|edu)" ;
System.out.println(str.matches(regex)) ;
}
}