Regular Expressions are highly efficient in processing strings.
The use of regular expressions involves more experience. If you are interested, refer to relevant books.
Here we mainly write the regular expression Operation Method in java.
Instance 1: Match
Copy codeThe Code is as follows: import java. util. collections;
Class Demo {
Public static void main (String [] args ){
Pipeline SC = new pipeline (System. in );
// Obtain input
System. out. print ("Please Enter :");
String str = SC. nextLine ();
Check (str );
}
Private static void check (String str ){
// Match the first digit with 1-9, and the second digit with 0-9 (the number is between 4-10)
String regex = "[1-9] [0-9] {4, 10 }";
/*
// Match the uppercase and lowercase letters of a single character
String regex = "[a-zA-Z]";
// Match numbers. Note the escape characters.
String regex = "\ d ";
// Match non-Numbers
String regex = "\ D ";
*/
If (str. matches (regex )){
System. out. println ("matched successfully ");
} Else {
System. out. println ("matching failed ");
}
}
}
The matches () method in the String class is used for matching.
Instance 2: Cut
Copy codeThe Code is as follows: import java. util. collections;
Class Demo {
Public static void main (String [] args ){
Pipeline SC = new pipeline (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 );
}
}
}
Here, the split () method in the String class is used to cut by regular expression, and a String array is returned.
Instance 3: replace
Copy codeThe Code is as follows: import java. util. collections;
Class Demo {
Public static void main (String [] args ){
Pipeline SC = new pipeline (System. in );
System. out. print ("Please Enter :");
String str = SC. nextLine ();
Replace (str );
}
Private static void replace (String str ){
// Match overlapping words
String regex = "(.) \ 1 + ";
String s = str. replaceAll (regex ,"*");
System. out. println (s );
}
}
Note that replaceAll has two parameters: Regular Expression and replacement character.