正则表达式
正则表达式:
定义:正确规则的表达式,他是一种独立的语法,很多语言都支持;
作用:就是校验数据,符不符合定义的这个正则表达式。
案例:
需求:检验QQ号是否合理
1: 要求必须是5 - 15 位数字
2: 0 不能开头
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入的你的QQ号");
String qqNumber = sc.nextLine();
boolean flag = checkQQNumber2(qqNumber);
if (flag) {
System.out.println("QQ号规则正确");
} else {
System.out.println("QQ号规则错误");
}
}
private static boolean checkQQNumber2(String qqNumber) {
String regx = "[1-9][0-9]{4,14}";
boolean b = qqNumber.matches(regx);
return b;
}
正则表达式定义:
String regx = "a";
regx = "[a,b,c]";
regx = "[a-z]";
regx = "[A,B,C,D]";
regx = "[A-Z]";
regx = "[a-zA-Z]";
regx = "[0,1,2,3]";
regx = "[0-9]";
regx = "[a-zA-Z0-9]";
regx = "[^0-9]";
regx = ".";
regx = "\\.";
regx = "|";
regx = "\\|";
regx = "\\d";
regx = "\\w";
regx = " ";
regx = "\\s";
regx = "abc$";
regx = "^abc";
regx = "[0-9]+";
regx = "[a-z]*";
regx = "[A-Z]?";
regx = "\\w+";
regx = "[a-zA-Z0-9_]+";
regx = "[a-z]{6}";
regx = "[a-zA-Z]{6,}";
regx = "[a-zA-Z]{6,16}";
正则表达式常用案例:
emailRegx = "[a-zA-Z]\\w{5,17}@[1-9a-z]{3,10}\\.(com|cn|net|org)";
boolean matches = "westos@163.net".matches(emailRegx);
System.out.println(matches);
String regx="[\\u4e00-\\u9fa5]{2,12}";
System.out.println("王老虎".matches(regx));
String shenFen="[1-9]\\d{5}(18|19|20|(3\\d))\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]";
String car="[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}";
根据正则来切割字符串
public static void main(String[] args) {
String names="张三=李四=王五";
String[] strings = names.split("=");
System.out.println(strings[0]);
System.out.println(strings[1]);
System.out.println(strings[2]);
}
正则表达式的替换功能
根据正则表达式(regex),将字符串不符合的正则的内容替换为指定内容(replecement);
String类的功能:public String replaceAll (String regex, String replacement);
案例:
public static void main(String[] args) {
String str2 = "abc你好abc";
String s = str.replaceAll("[^\\u4e00-\\u9fa5]", "");
System.out.println(s);
}
正则表达式的查找和获取功能
boolean find ();尝试查找与该模式匹配的输入序列的下一个子序列。
String group ();返回由以前匹配操作所匹配的输入子序列。
案例:
public static void main(String[] args) {
String str="da jia ting wo shuo, jin tian yao xia yu, bu shang wan zi xi, gao xing bu?";
String regx="\\b[a-z]{3}\\b";
Pattern pattern = Pattern.compile(regx);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
String s = matcher.group();
System.out.println(s);
}
}
正则的模式器和匹配器
Pattern pattern = Pattern.compile(regx);
Matcher matcher = pattern.matcher(str);
案例:
public static void main(String[] args) {
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
System.out.println(b);
System.out.println("aaaaab".matches("a*b"));
}