一、匹配
1public class RegularExpressionDemo{ 2 public static void main(String[] args){ 3 4 //匹配电话号码 5 String telphoneNum= "0015012828944"; 6 String reg= "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$"; 7 System.out.println(telphoneNum.matches(reg)); 8 9 } 10}
二、切割
1public class RegularExpressionDemo{ 2 public static void main(String[] args){ 3 4 //把语句切割为单词 5 String sentence = "welcome to china "; 6 String reg = " +"; 7 String[] words = sentence.split(reg); 8 for(String word : words){ 9 System.out.println(word); 10 } 11 } 12}
三、替换
1public class RegularExpressionDemo{ 2 public static void main(String[] args){ 3 4 //把字符串中的标点符号换成空 5 String sentence = "How are you? Fine, thanks."; 6 String reg = "[?,.]"; 7 sentence = sentence.replaceAll(reg,""); 8 System.out.println(sentence); 9 } 10}
四、获取
1import java.util.regex.Pattern; 2import java.util.regex.Matcher; 3 4public class RegularExpressionDemo{ 5 public static void main(String[] args){ 6 7 //获取句子中所有长度为3的单词 8 String sentence = "How old are you? I'm 27 years old. what about you? So am I."; 9 String reg = "[a-zA-Z]{3}"; 10 11 Pattern p = Pattern.compile(reg); 12 Matcher m = p.matcher(sentence); 13 14 while(m.find()){ 15 System.out.println(m.group()); 16 } 17 } 18}