1.正则表达式的概念
2.应用
单个字符的匹配(字母、数字、字符、字符串…
public static void main(String[] args) {
String a="f12";
String regex="[fab][0-9][0-9]";
System.out.println(a.matches(regex));
}
public static void main(String[] args) {
String str="e$@";
String regex="[^0-9a-z][0-9][0-9]";
System.out.println(str.matches(regex));
}
public static void main(String[] args) {
String gender = "保密";
String regex = "[男]| [女]|(保密)";
System.out.println(gender.matches(regex));
}
多个字符的匹配(匹配0、1、n次…/号码/身份证匹配…
public static void main(String[] args) {
String str="123456";
String regex="[0-9]{6}";
System.out.println(str.matches(regex));
String regex4="[0-9]{6,}";
String regex6="[0-9]+";
String regex9="[0-9]*";
String regex10="[0-9]?";
String regex5="[0-9]{6,12}";
String regex7="\\d+";
String phonenum="1500000000";
String regex2="[1][0-9]{10}";
System.out.println(phonenum.matches(regex2));
String identityNum="350000000000000000";
String regex3="[1-9][0-9]{16}[0-9X]";
System.out.println(identityNum.matches(regex3));
}
找出字符串中的中文并输出
public class String14 {
public static void main(String[] args) {
String str="djjab点击dhsfJD3E3N的2JBJJ大家B341";
String regex="[^\u4e00-\u9fa5]+";
String s=str.replaceAll(regex, "");
System.out.println(s);
}
}
统计字符串中指定字符(apple)出现次数
public static void main(String[] args) {
String a="there are one apple,two apples,three apples,many apples,how many apples i have?";
f(a);
System.out.println("苹果"+b);
static int b=0;
public static void f(String a) {
int index =a.indexOf("apple");
if(index==-1) {
return;
}
b++;
f(a.substring(index+"apple".length()));
}