加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达的式的基本功能

发布时间:2020-12-14 01:41:25 所属栏目:百科 来源:网络整理
导读:在开发中,正则表达式有很大的用途的,现在说说它最基本的4个常用的功能: 查询、提

在开发中,正则表达式有很大的用途的,现在说说它最基本的4个常用的功能:

查询、提取、分割、替换,用代码说话,看看就明白了

 
  1. packagecom.sucre.blog;
  2. importjava.util.regex.Matcher;
  3. importjava.util.regex.Pattern;
  4. /**
  5. *正则表达式的常用功能测试
  6. *@authorsucre
  7. *
  8. */
  9. publicclassRegularExpressions{
  10. /**
  11. *查询str中是否有regEx,有rs为true,否则为flase
  12. *@return
  13. */
  14. privatestaticvoidsearchCharacter(){
  15. Stringstr="sucreblog51CTO.COM";
  16. StringregEx="c|l";//表示a或f
  17. Patternp=Pattern.compile(regEx);
  18. //这种写法是忽略大小写的
  19. //Patternp=Pattern.compile(regEx,Pattern.CASE_INSENSITIVE);
  20. Matcherm=p.matcher(str);
  21. booleanrs=m.find();
  22. System.out.println(rs);
  23. }
  24. /**
  25. *提取字符串
  26. *结果为name.txt,提取的字符串储存在m.group(i)中,其中i最大值为m.groupCount();
  27. */
  28. privatestaticvoidextraction(){
  29. StringregEx="(.+)$";
  30. Stringstr="c:name.txt";
  31. Patternp=Pattern.compile(regEx);
  32. Matcherm=p.matcher(str);
  33. booleanrs=m.find();
  34. for(inti=1;i<=m.groupCount();i++){
  35. System.out.println(m.group(i));
  36. }
  37. }
  38. /**
  39. *分割字符串
  40. *
  41. */
  42. privatestaticvoidsegmentation(){
  43. StringregEx="::";
  44. Patternp=Pattern.compile(regEx);
  45. String[]r=p.split("sucre::blog::51cto");
  46. for(inti=0;i<r.length;i++){
  47. System.out.println(r[i]);
  48. }
  49. }
  50. /**
  51. *替换字符
  52. *
  53. */
  54. privatestaticvoidreplace(){
  55. StringregEx="a+";//表示一个或多个a
  56. Patternp=Pattern.compile(regEx);
  57. Matcherm=p.matcher("aaabbcedaccdeaa");
  58. Strings=m.replaceAll("A");
  59. System.out.println(s);
  60. }
  61. publicstaticvoidmain(String[]args){
  62. searchCharacter();
  63. extraction();
  64. segmentation();
  65. replace();
  66. }
  67. }

运行结果为

 
  1. true
  2. c:name.txt
  3. sucre
  4. blog
  5. 51cto
  6. AbbcedAccdeA

许多复杂的功能都是在这些简单功能的基础上构建起来的,基础很重要。

本文出自 “乔磊的博客 学习 进步” 博客,请务必保留此出处http://www.52php.cn/article/p-bmkgarja-bhq.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读