Regular expressions are quite efficient at handling strings.
About the use of regular expressions, more of their own experience, interested can refer to related books
This is mainly written in Java in the regular operation method
Instance 1: Matching
Copy Code code as follows:
Import Java.util.Scanner;
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 match is 1-9, the second and the next 0-9 (the number is between 4-10)
String regex = "[1-9][0-9]{4,10}";
/*
Matching a single character is the case of a-Z
String regex = "[A-za-z]";
Match numbers, note escape characters
String regex = "\\d";
Match non-numeric
String regex = "\\d";
*/
if (Str.matches (regex)) {
System.out.println ("matching success");
} else {
System.out.println ("Match failed");
}
}
}
The matches () method in the string class here is used to match
Example 2: Cutting
Copy Code code as follows:
Import Java.util.Scanner;
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);
}
}
}
The split () method in the string class here is used to cut by regular expression, returning a string array
Example 3: Replacing
Copy Code code as follows:
Import Java.util.Scanner;
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) {
Matching overlapping words
String regex = "(.) \\1+ ";
String s = str.replaceall (Regex, "*");
System.out.println (s);
}
}
Note that the ReplaceAll has two parameters, one is regular, the other is a substituted character