java.long.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)
案例, 找出字符串中的字母
package com.cwq.beyond;
public class test22 {
public static void main(String[] args) {
String str = "@#@#fdsafSJHFK&*(IDHFK^F(#@HJHKJsdfsafw213214KJHdsf*^#Jkh324jk2#@";
String regex = "[^a-zA-Z]";
System.out.println(str.replaceAll(regex, ""));
}
}
案例: 字符串拆分(按数字拆分)
package com.cwq.beyond;
public class test22 {
public static void main(String[] args) {
String str = "aaaa980943bbbUUER89wer89Jjls";
String regex = "\\d+";
String data[] = str.split(regex);
for (int i = 0; i < data.length; i++) {
System.out.println(data[i]);
}
}
}
案例: 验证字符串是否是数字(包括整数和小数),如果是要变成Double型
package com.cwq.beyond;
public class test22 {
public static void main(String[] args) {
String str = "11011";
String regex = "\\d+(\\.\\d+)?";
if (str.matches(regex)) {
Double data = Double.parseDouble(str);
System.out.println(data);
}
}
}
案例: 判断一个字符串是否是日期类型, 是则转化成Date型
package com.cwq.beyond;
import java.text.SimpleDateFormat;
public class test22 {
public static void main(String[] args) throws Exception{
String str = "2020-10-12 14:45:12";
String regex = "\\d{4}-\\d{2}-\\d{2}";
if (str.matches(regex)) {
System.out.println(new SimpleDateFormat("yyyy-MM-dd").parse(str));
}else if (str.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")) {
System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(str));
}
}
}
案例: 判断给定的电话号码格式是否正确
package com.cwq.beyond;
import java.text.SimpleDateFormat;
public class test22 {
public static void main(String[] args) throws Exception{
String str[] = {"12345678","01012345678","(010)-12345678"};
String regex = "(\\()?(\\d{3,4})?(\\)-)?\\d{7,8}";
for (int i = 0; i < str.length; i++) {
if (str[i].matches(regex)) {
System.out.println("格式正确");
}else {
System.out.println("格式错误");
}
}
}
}