Regular

不念不忘少年蓝@ 2021-09-11 07:12 289阅读 0赞
  1. import java.util.regex.Matcher;
  2. import java.util.regex.Pattern;
  3. public class Regularj {
  4. /* 2017-02-16 13:16:05
  5. * matches 判断是否匹配指定的正则表达式
  6. * replaceAll 将一个字符串替换为指定的值
  7. * replacefirst 将字符串中第一个匹配的 指定的子串替换成
  8. *
  9. * 预定义字符
  10. * . 匹配任何字符
  11. * \d 匹配 0-9
  12. * \D 非数字
  13. * \s 匹配所有的空白字符,包括空格、制表符、回车符、换页符、换行符
  14. * \S 匹配所有非空白字符
  15. * \w 匹配所有的单词字符 包括0-9 26个字母 下划线
  16. * \W 匹配非单词的字符
  17. *
  18. * digit 数字
  19. * space 空格
  20. * word 单词
  21. *
  22. * 枚举 [asdf] asdf 中的任意一个
  23. * 范围 - a-c a到c 中的任意字符
  24. * 否 ^ [^asd] 不是asd
  25. * 与 && 求交集 [a-d && [bc]] 表示bc
  26. * 并 [a-d[m-p]] == [a-dm-p]
  27. *
  28. *
  29. * 边界匹配符
  30. * ^ 行的开头
  31. * $ 行的结尾
  32. * \b 单词的边界
  33. * \B 非单词的边界
  34. * \A 输入的开头
  35. * \G 前一个匹配的结束
  36. * \Z 输入的结尾、仅用于最后的结束符
  37. * \z 输入的结尾
  38. *
  39. * greedy 贪婪模式 数量表示符默认采用贪婪模式 除非另有表示,否则 直到无法匹配为止
  40. *
  41. * reluctant 勉强模式 用问号后缀 ? 表示 只会匹配最少的字符,也称为最小匹配模式
  42. * possessive 占有模式 + 表示
  43. *
  44. *
  45. * 使用正则表达式
  46. * Pattern 和matcher 对象
  47. *
  48. * Pattern 对象是正则表达式编译后在内存中的表示形式,因此正则表达式字符串必须先被编译为pattern 对象 。
  49. * 然后再利用pattern对象创建对应的matcher对象
  50. * 执行匹配所涉及的状态保留在matcher对象中
  51. * 多个matcher 对象可共享同一个pattern对象
  52. *
  53. */
  54. public static void main(String[] args) {
  55. // 正则表达式
  56. String string = "string,string,string";
  57. System.out.println(string.replaceFirst("\\w*", "-")); // 贪婪模式 -,string,string
  58. System.out.println(string.replaceFirst("\\w?", "-")); // 勉强模式 -tring,string,string
  59. // matcherj();
  60. // matcherfindj();
  61. }
  62. /* 2017-02-16 14:19:41
  63. *
  64. */
  65. private static void matcherfindj() {
  66. String string2 = "13012345678" + "asd" + "12345678123" + "asd" + "45812345678" +"asd" + "130123456789";
  67. Pattern pattern = Pattern.compile("((13\\d)|(12\\d))\\d{8}"); //匹配 13 或者12 开头 后面面8位
  68. Matcher matcher = pattern.matcher(string2);
  69. while (matcher.find()) {
  70. //find方法依次查找字符串中与pattern匹配的子串,一旦找到,下次调用将接着向下找
  71. //还可以传入int 参数 从int 位置开始查找
  72. System.out.println(matcher.group());
  73. }
  74. }
  75. /* 2017-02-16 14:08:07
  76. *
  77. */
  78. private static void matcherj() {
  79. Pattern pattern = Pattern.compile("asd"); // 将一个字符串编译成pattern对象
  80. Matcher matcher = pattern.matcher("aaaaaaaa"); // 使用pattern对象创建matcher对象
  81. boolean b = matcher.matches();
  82. boolean b2 = Pattern.matches("asd", "aaaa"); //如果pattern对象只使用一次,可以用pattern 的matches 静态方法
  83. //patt 是不可变类,可供多个并发线程安全使用
  84. //matcher 的常用方法
  85. // matcher.find()
  86. // matcher.group()
  87. // matcher.start()
  88. // matcher.end()
  89. // matcher.lookingAt()
  90. // matcher.matches()
  91. // matcher.reset(input)
  92. //charsequence 接口,该接口代表一个字符序列
  93. //charbuffer string StringBuffer StringBuilder 都是它的实现类, CharSequence 代表一个各种表示形式的字符串
  94. }
  95. }

发表评论

表情:
评论列表 (有 0 条评论,289人围观)

还没有评论,来说两句吧...

相关阅读