- 正则替换
package cn.dujiang.demo;
/**
*正则替换,将大写字母替换成了空字符串,输出的就是小写字母咯
* @author Dujiang
*
*/
public class TestDemo {
public static void main(String[] args) throws Exception {
String str = "JHFUKFYLUIjsuadaJHKHi&*^$&($_)&:“《》?《";
String regex = "[^a-z]"; //把不是小写字母的摘出来,放到一个人空的字符串中
System.out.println(str.replaceAll(regex, ""));
}
}
- 正则字符串的拆分
package cn.dujiang.demo;
/**
*以数字为分割线,把代码进行了拆分
* @author Dujiang
*
*/
public class TestDemo {
public static void main(String[] args) throws Exception {
String str = "145HHhh7645sa:“L[p;[jk45s2a3hy|";
String regex = "\\d+"; //表示一位及一位以上数字的拆分
String result[] = str.split(regex) ;
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}
}
- 正则判断验证字符串
package cn.dujiang.demo;
/**
*验证一个字符串是否是数字,如果是则将其变为double型
*1.数字有可能整数也可能是小数
* @author Dujiang
*
*/
public class TestDemo {
public static void main(String[] args) throws Exception {
String str = "10.1" ;
String regex = "\\d+(\\.\\d+)?" ; //注意一定要把"."和点后的数字当成一个整体,这个整体要么出现一次,要么不出现
System.out.println(str.matches(regex));
if (str.matches(regex)) {//转型之前要进行验证
System.out.println(Double.parseDouble(str));
}
}
}
- 判定给定字符串的地址
package cn.dujiang.demo;
/**
*判断给定的字符串是否是一个IP地址(IPV4)
* @author Dujiang
*
*/
public class TestDemo {
public static void main(String[] args) throws Exception {
String str = "192.0.1.1" ;
String regex = "(\\d{1,3}\\.){3}\\d{1,3}" ;
System.out.println(str.matches(regex));
}
}
/*package cn.dujiang.demo;
public class TestDemo {
public static void main(String[] args) throws Exception {
String str = "192.0.1.1" ;
String regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}" ;
System.out.println(str.matches(regex));
}
}
*/
℃江