正则表达式

////匹配

使用的是String中的matches()方法

//////分割

使用的是String中的split()方法

///替换

使用的是String中的replaceAll()方法

  1. packagecom.xuan.demo;
  2. importjava.util.regex.Matcher;
  3. importjava.util.regex.Pattern;
  4. publicclassRegexDemo{
  5. publicstaticvoidmain(String[]args){
  6. System.out.println("正则表达式");
  7. ///匹配
  8. RegexFunction2();
  9. ///分割
  10. sqplitDemo();
  11. ///替换
  12. replaceAllDemo();
  13. //获取
  14. PatternDemo();
  15. }
  16. publicstaticvoidPatternDemo(){
  17. Stringstr="nilovming,xixi,hahaIloveYou,fanxiaoxiao,jiadashu";
  18. //Stringregex="[a-z]{3}";///这写法获取有问题,没有指定边界
  19. Stringregex="\\b[a-z]{3}\\b";//有指定边界
  20. //将正则封装成对象
  21. Patternp=Pattern.compile(regex);
  22. //通过正则获取匹配对象
  23. Matcherm=p.matcher(str);
  24. //m.find();///查找,找到返回true
  25. while(m.find()){
  26. System.out.println("-----:"+m.group());
  27. }
  28. publicstaticvoidreplaceAllDemo(){
  29. Stringstr="xixitttttthahaniniwwwwwwwwwhehe";
  30. ///将叠词替换成#号
  31. //str=str.replaceAll("(.)\\1+","#");//把连续重复的替换成#号
  32. str=str.replaceAll("(.)\\1+","$1");//把连续重复的替换成一个:==>xixithahaniniwhehe
  33. System.out.println("======>"+str);
  34. Stringtel="15800001111";
  35. ///(\\d{3})封装成组$1,(\\d{4})封装成组$2
  36. tel=tel.replaceAll("(\\d{3})\\d{5}(\\d{3})","$1****$2");
  37. System.out.println("=====>"+tel);///===>158****111
  38. publicstaticvoidsqplitDemo(){
  39. Stringstr="xiaomingwangcaixiaoqiangxiaoli";
  40. String[]names=str.split("\\");
  41. /*Stringstr="xiaoming.wangcai.xiaoqiang";
  42. String[]names=str.split("\\.");*/
  43. for(Stringname:names){
  44. System.out.println("----->"+name);
  45. publicstaticvoidRegexFunction2(){
  46. ///手机校验
  47. ///第一位只能为1,第二位:只能是3,5,8,;后面9位数只能是数字,不能出现字母
  48. //Stringregex="1[358][0-9]{9}";
  49. Stringregex="1[358]\\d{9}";//简写
  50. booleanb=tel.matches(regex);
  51. System.out.println(tel+"==>"+b);
  52. }

相关文章

正则替换html代码中img标签的src值在开发富文本信息在移动端...
正则表达式
AWK是一种处理文本文件的语言,是一个强大的文件分析工具。它...
正则表达式是特殊的字符序列,利用事先定义好的特定字符以及...
Python界一名小学生,热心分享编程学习。
收集整理每周优质开发者内容,包括、、等方面。每周五定期发...