1、正则标记(背)
1、替换和拆分
public class RegexDemo1 { public static void main(String[] args) { String str1 = "ojd02n9dkas333-222-//"; String regex = "[^a-z]"; System.out.println(str1.replaceAll(regex,"")); //正则替换 String regex1 = "\\d+"; String [] result = str1.split(regex1); //以数字拆分 for (String i:result){ System.out.print(i); } } }
2、判断一个字符是否是数字,也可能是小数。并将其转换为Double型。
public class RegexDemo2 { public static void main(String[] args) { String str = "10."; String regex = "\\d+(\\.\\d+)?"; if (str.matches(regex)){ System.out.println(Double.parseDouble(str)); }else { return; } } }
3、判断一个字符串是否是IP地址
String str1 = "192.168.1.1"; String regex2 = "(\\d{1,3}\\.){3}\\d{1,3}"; System.out.println(str1.matches(regex2));
4、判断是否是日期格式
String str = "2020-06-29"; String regex = "\\d{4}-\\d{2}-\\d{2}"; if (str.matches(regex)){ Date date = new SimpleDateFormat("yyyy-MM-dd").parse(str); System.out.println(date); }
5、
String str = "(010)-1234567"; String regex = "((\\d{3,4}-)|(\\(\\d{3,4}\\)-))?\\d{7,8}"; System.out.println(str.matches(regex));