Learn Java regular expressions (match replace find)
- 2020-04-01 04:30:44
- OfStack
This article for you to share the Java regular expression match, replace, find and cut operations, interested friends can refer to
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class test {
public static void main(String[] args) {
getStrings(); //Gets the specified content in the specified string content with a regular expression
System.out.println("********************");
replace(); //Replace the string content with a regular expression
System.out.println("********************");
strSplit(); //Use regular expressions to cut strings
System.out.println("********************");
strMatch(); //String matching
}
private static void strMatch() {
String phone = "13539770000";
//Check whether the phone is a qualified phone number (standard :1, 3,5,8 in the second place, 9 in any number)
System.out.println(phone + ":" + phone.matches("1[358][0-9]{9,9}")); //true
String str = "abcd12345efghijklmn";
//Check whether there is 12345 in the middle of STR
System.out.println(str + ":" + str.matches("\w+12345\w+")); //true
System.out.println(str + ":" + str.matches("\w+123456\w+")); //false
}
private static void strSplit() {
String str = "asfasf.sdfsaf.sdfsdfas.asdfasfdasfd.wrqwrwqer.asfsafasf.safgfdgdsg";
String[] strs = str.split("\.");
for (String s : strs){
System.out.println(s);
}
}
private static void getStrings() {
String str = "rrwerqq84461376qqasfdasdfrrwerqq84461377qqasfdasdaa654645aafrrwerqq84461378qqasfdaa654646aaasdfrrwerqq84461379qqasfdasdfrrwerqq84461376qqasfdasdf";
Pattern p = Pattern.compile("qq(.*?)qq");
Matcher m = p.matcher(str);
ArrayList<String> strs = new ArrayList<String>();
while (m.find()) {
strs.add(m.group(1));
}
for (String s : strs){
System.out.println(s);
}
}
private static void replace() {
String str = "asfas5fsaf5s4fs6af.sdaf.asf.wqre.qwr.fdsf.asf.asf.asf";
//Replace the. In the string with _, because. Is a special character, express it with ., and because is a special character, express it with .
str = str.replaceAll("\.", "_");
System.out.println(str);
}
}
The key points of the code have been noted for you, I hope you can study carefully, from which to summarize the learning skills.