Regular expressions are quite efficient in processing strings
Regarding the use of regular expressions, it is more about my own experience. If you are interested, you can refer to relevant books.
Here we mainly write about the regular operation methods in java
Example 1: Match class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//Get input
System.out.print("Please Enter:");
String str = sc.nextLine();
check(str);
}
private static void check(String str) {
//The first matching digit is 1-9, the second and subsequent digits are 0-9 (the number is between 4-10)
String regex = "[1-9][0-9]{4,10}";
/*
//Match a single character that is uppercase or lowercase az
String regex = "[a-zA-Z]";
//Match numbers, pay attention to escape characters
String regex = "//d";
//match non-digits
String regex = "//D";
*/
if(str.matches(regex)) {
System.out.println("Matching successful");
} else {
System.out.println("Matching failed");
}
}
}
Example 2: Cutting
class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please Enter:");
String str = sc.nextLine();
split(str);
}
private static void split(String str) {
//Match one or more spaces
String regex = " +";
String[] arr = str.split(regex);
for (String s : arr) {
System.out.println(s);
}
}
}
Example 3: Replacement
class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please Enter:");
String str = sc.nextLine();
replace(str);
}
private static void replace(String str) {
//Match repeated words
String regex = "(.)//1+";
String s = str.replaceAll(regex, "*");
System.out.println(s);
}
}