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