2013-08-21 14:35 3325人阅读 评论(0) 收藏 举报
 分类:
JavaSE(30) 

版权声明:本文为博主原创文章,未经博主允许不得转载。

 

目录(?)[+]

 

正则表达式概念

  1. 所谓正则表达式就是处理字符串的特殊字符串
  2. 用途
  3. 字符串匹配(字符匹配)
  4. 字符串查找(是建立在匹配之上的查找)
  5. 字符串替换(是建立在查找的结果之后的替换)
  6. 例如
  7. IP地址是否正确
  8. 从网页中揪出Email地址
  9. 从网页揪出链接
  10. java.lang.String
  11. java.util.regex.Pattern
  12. java.util.regex.Matcher
  13. 要点
  14. //一个反斜线
  15. String str1 = "\\";
  16. //正则表达式的一个反斜线使用两个反斜线,在java中表示就再需要两个反斜线转义
  17. System.out.println(str1.matches("\\\\"));
  18. //POSIX Style,这种写法不建议使用,如果要使用查API
  19. System.out.println("a".matches("\\p{Lower}"));
  20. //空白行
  21. " \n".matches("^[\\s&&[^\n]]*\\n$");
  22. //邮箱
  23. String regex1 = "[\\w[.-]]+";
  24. String regex2 = "@";
  25. String regex3 = "[\\w[.-]]+";
  26. String regex4 = "\\.";
  27. String regex5 = "[\\w]+";
  28. String regex = regex1+regex2+regex3+regex4+regex5;
  29. System.out.println("156112846@qq.com".matches(regex));

正则表达式的基本语法

  1. 普通字符(字母,数字,汉字,下划线)
  2. 一个普通字符在表达式中只匹配与之相同的一个字符
  3. 表达式k在字符串sky进行匹配时,将匹配成功
  4. \r,\n,\t,\f
  5. 表示回车符,换行符,制表符,换页符
  6. .
  7. 任意一个字符
  8. X?
  9. 表示X可以出现0次或者1次
  10. X+
  11. 表示X可以出现1次或者多次
  12. X*
  13. 表示X可以出现任意次
  14. X{n}
  15. 表示X可以出现n次
  16. X{m,n}
  17. 表示X可以最少出现m次,最多出现n次
  18. X{n,}
  19. 表示X最少出现n次
  20. [ ]
  21. 匹配中括号中任意一个字符
  22. [^ ]
  23. 匹配中括号中字符之外的任意一个字符
  24. \d
  25. 表示0~9之间的任意一个数字字符,即[0-9]
  26. \D
  27. 表示0~9之外的任意数字字符,即[^0-9]
  28. \r,\n,\t,\f
  29. 表示回车符,换行符,制表符,换页符
  30. \s
  31. 表示空格,制表符,换页符等空白字符的任意一个
  32. \S
  33. 表示空白字符以外的任意一个字符,即[^\s]
  34. \w
  35. 表示字母,数字,下划线中的任意一个字符,即[a-zA-Z_0-9]
  36. \W
  37. 表示字母,数字,下划线以外的任意一个字符,即[^a-zA-Z_0-9]
  38. ^
  39. 该符号不匹配任何字符,字符串开始的位置,即^h必须以h开头
  40. $
  41. 该符号不匹配任何字符,字符串结束的位置,即r$必须以r结尾
  42. \b
  43. 该符号不匹配任何字符,表示单词的边界
  44. \B
  45. 该符号不匹配任何字符,表示非单词的边界,即[^\b]
  46. |
  47. 用来连接两个表达式,表示或的关系
  48. X|Y 表示X或者Y中的任意字符
  49. ()
  50. 作为一个单元,一个分组
  51. \n(n表示一个数字)
  52. 有分组的情况下,表示对分组的引用
  53. \1表示对分组1的引用
  54. \
  55. 转义字符,当一个符号自身有意义而又要表示这个字符的时候,就需要转义
  56. \^表示^,\$表示$
  57. ?
  58. 如果在?,+,*,{n},{m,n},{n,}后面,表示次数按非贪婪模式进行匹配,
  59. 即按照匹配模式进行最小限度的匹配

扩展内容

 

贪婪 VS 非贪婪 VS 独占

  1. package com.itlwc;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4. public class Test {
  5. public static void main(String[] args) throws Exception {
  6. String str = "aaaa5bbbb6";
  7. /*
  8. * 贪婪的
  9. * 一次吃进最多的10个字符,不匹配,再吐出来一个,匹配了,结束了
  10. */
  11. String regex1 = ".{3,10}[0-9]";
  12. Matcher m1 = Pattern.compile(regex1).matcher(str);
  13. if (m1.find())
  14. System.out.println(m1.start() + "-" + m1.end());
  15. else
  16. System.out.println("not match!");
  17. /*
  18. * 非贪婪的
  19. * 一次吃进最少的3个字符,然后看后面哪个是不是数字,
  20. * 再吞一个,然后再看后面哪个是不是数字,匹配了,结束了
  21. */
  22. regex1 = ".{3,10}?[0-9]";
  23. m1 = Pattern.compile(regex1).matcher(str);
  24. if (m1.find())
  25. System.out.println(m1.start() + "-" + m1.end());
  26. else
  27. System.out.println("not match!");
  28. /*
  29. * 独占的
  30. * 一次吃进最多的10个字符,不匹配,不吐出来,不匹配了,结束了
  31. */
  32. regex1 = ".{3,10}+[0-9]";
  33. m1 = Pattern.compile(regex1).matcher(str);
  34. if (m1.find())
  35. System.out.println(m1.start() + "-" + m1.end());
  36. else
  37. System.out.println("not match!");
  38. }
  39. }
  40. /*
  41. 打印结果:
  42. 0-10
  43. 0-5
  44. not match!
  45. */

非捕获组

  1. package com.itlwc;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4. public class Test {
  5. public static void main(String[] args) throws Exception {
  6. System.out.println("--打印以a结尾的子串---");
  7. String str = "444a66b";
  8. String regex = ".{3}a";
  9. Matcher m = Pattern.compile(regex).matcher(str);
  10. while (m.find())
  11. System.out.println(m.group());
  12. System.out.println("--打印以a结尾的子串,但不捕获a--");
  13. // 非捕获组,这块的意思是不捕获a,算在这三个字符之中的
  14. regex = ".{3}(?=a)";
  15. m = Pattern.compile(regex).matcher(str);
  16. while (m.find())
  17. System.out.println(m.group());
  18. System.out.println("--这个例子和上面例子相似,但结果出乎意料--");
  19. // 非捕获组,不算在这三个字符之中的
  20. regex = "(?=a).{3}";
  21. m = Pattern.compile(regex).matcher(str);
  22. while (m.find())
  23. System.out.println(m.group());
  24. System.out.println("--打印前面不能是a的子串");
  25. regex = "(?!a).{3}";
  26. m = Pattern.compile(regex).matcher(str);
  27. while (m.find())
  28. System.out.println(m.group());
  29. System.out.println("--这个例子和上面例子相似,结果需要注意--");
  30. // 这个是先找444,后面是a不匹配再找44a,后面不是a,匹配
  31. regex = ".{3}(?!a)";
  32. m = Pattern.compile(regex).matcher(str);
  33. while (m.find())
  34. System.out.println(m.group());
  35. regex = ".{3}(?<!a)";
  36. }
  37. }
  38. /*
  39. 打印结果:
  40. --打印以a结尾的子串---
  41. 444a
  42. --打印以a结尾的子串,但不捕获a--
  43. 444
  44. --这个例子和上面例子相似,但结果出乎意料--
  45. a66
  46. --打印前面不能是a的子串
  47. 444
  48. 66b
  49. --这个例子和上面例子相似,结果需要注意--
  50. 44a
  51. 66b
  52. */

向前引用

  1. package com.itlwc;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4. public class Test {
  5. public static void main(String[] args) throws Exception {
  6. // 第一组找到12,\1的意思是后面的必须和第一组一样
  7. Matcher m1 = Pattern.compile("(\\d\\d)\\1").matcher("1212");
  8. System.out.println(m1.matches());
  9. //1212不匹配,121不匹配,122匹配
  10. Matcher m2 = Pattern.compile("(\\d(\\d))\\2").matcher("1212");
  11. System.out.println(m2.matches());
  12. }
  13. }
  14. /*
  15. 打印结果:
  16. true
  17. false
  18. */

flags简写

  1. package com.itlwc;
  2. import java.util.regex.Pattern;
  3. public class Test {
  4. public static void main(String[] args) throws Exception {
  5. Pattern.compile("java", Pattern.CASE_INSENSITIVE);
  6. //上下代码是等价的
  7. System.out.println("JAVA".matches("(?i)(java)"));
  8. System.out.println("java".matches("(?i)(java)"));
  9. }
  10. }
  11. /*
  12. 打印结果:
  13. true
  14. true
  15. */

String中正则表达式的使用

  1. package com.itlwc;
  2. public class Test {
  3. public static void main(String[] args) throws Exception {
  4. String str = "abc:0000:defg";
  5. System.out.println(str.replace("0000","8765"));
  6. // 替换所有匹配正则表达式的
  7. System.out.println(str.replaceAll("\\d", "0"));
  8. // 只替换第一个匹配正则表达式的
  9. System.out.println(str.replaceFirst("\\d", "1"));
  10. // str是否匹配给定正则表达式
  11. System.out.println(str.matches(".{13}"));
  12. //拆分
  13. for(String s : str.split(":")){
  14. System.out.print(s+"\t");
  15. }
  16. System.out.println();
  17. //拆分几段
  18. for(String s : str.split(":",2)){
  19. System.out.print(s+"\t");
  20. }
  21. }
  22. }
  23. /*
  24. 打印结果:
  25. abc:8765:defg
  26. abc:0000:defg
  27. abc:1000:defg
  28. true
  29. abc 0000    defg
  30. abc 0000:defg
  31. */

Pattern概述

  1. java.util.regex.Pattern
  2. 其对象表示通过编译的正则式,利用该类对象可以与任意字符串进行模式匹配
  3. 构造器
  4. Pattern类的构造器是private
  5. 声明
  6. public final class Pattern extends Object implements Serializable
  7. 创建Pattern的静态工厂
  8. public static Pattern compile(String regex)
  9. 将指定正则式编译成Pattern对象返回
  10. public static Pattern compile(String regex,int flags)
  11. 将指定正则式按照指定标志编译成Pattern对象返回

Pattern标志常量

  1. public static final int CASE_INSENSITIVE
  2. 将启动对ASCII字符不区分大小写匹配
  3. public static final int UNICODE_CASE
  4. 将启动Unicode字符不区分大小写匹配
  5. public static final int DOTALL
  6. 将启动dotall模式,该模式下,"."将表示任意字符,包括回车符

Pattern常用方法

  1. package com.itlwc;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4. public class Test {
  5. public static void main(String[] args) throws Exception {
  6. // 编译好的模式用起来更快一些
  7. // 将给定的正则表达式编译到模式中
  8. Pattern p = Pattern.compile("[a-z]{3}");
  9. // 将给定的正则表达式编译到具有给定标志的模式中
  10. p = Pattern.compile("[a-z]{3}", Pattern.CASE_INSENSITIVE);
  11. // 返回此模式的匹配标志
  12. System.out.println(p.flags());
  13. // 匹配某个字符串之后的结果,这个有可能有很多个
  14. // 该方法返回表示将要被匹配字符序列的匹配器对象
  15. Matcher m = p.matcher("fgh");
  16. System.out.println(m.matches());
  17. // 编译给定正则表达式并尝试将给定输入与其匹配
  18. System.out.println(Pattern.matches("[a-z]{3}", "fgh"));
  19. // 返回在其中编译过此模式的正则表达式
  20. System.out.println(p.pattern());
  21. // 该方法返回指定字符串的模式文本表示
  22. System.out.println(Pattern.quote("abc"));
  23. // 匹配拆分
  24. String[] str1 = Pattern.compile(",").split("boo,and,foo");
  25. for (String s : str1) {
  26. System.out.print(s + "\t");
  27. }
  28. System.out.println();
  29. // 匹配拆分,拆分几段
  30. String[] str2 = Pattern.compile(":").split("boo:and:foo", 2);
  31. for (String s : str2) {
  32. System.out.print(s + "\t");
  33. }
  34. }
  35. }
  36. /*
  37. 打印结果:
  38. 2
  39. true
  40. true
  41. [a-z]{3}
  42. \Qabc\E
  43. boo and foo
  44. boo and:foo
  45. */

Matcher概述

  1. java.util.regex.Matcher 匹配器
  2. 声明
  3. public final class Matcher extends Object implements MatchResult

Matcher常用方法

  1. package com.itlwc;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4. public class Test {
  5. public static void main(String[] args) throws Exception {
  6. Matcher m1 = Pattern.compile("\\d{3,5}").matcher("123-45682-152-00");
  7. // 返回由此匹配器解释的模式
  8. System.out.println(m1.pattern());
  9. // 只有整个字符序列完全匹配成功才返回true
  10. System.out.println(m1.matches());
  11. // 把原来吃点的吐出来恢复到从前的状态
  12. m1.reset();
  13. // 找一个和模式匹配的子串,找到之后正则表达式引擎会把第一个子串去掉
  14. System.out.println(m1.find());
  15. // 起始位置和结束位置,但必须能找到,否则报错
  16. System.out.println(m1.start() + "-" + m1.end());
  17. // 每次都从开始位置找
  18. System.out.println(m1.lookingAt());
  19. System.out.println("------------------------------");
  20. CharSequence cs = "java JAVA javaEE hiJAVA abcdefg";
  21. int i = Pattern.CASE_INSENSITIVE;
  22. Matcher m2 = Pattern.compile("java", i).matcher(cs);
  23. while (m2.find()) {
  24. // 分组,输出匹配到的子串
  25. System.out.print(m2.group() + "\t");
  26. }
  27. System.out.println();
  28. System.out.println("------------------------------");
  29. // 把java全部替换成JAVA
  30. System.out.println(m2.replaceAll("JAVA"));
  31. System.out.println("------------------------------");
  32. // 把单数java转换为小写,双数java转换为大写
  33. m2.reset();
  34. StringBuffer sb = new StringBuffer();
  35. int count = 0;// 奇数偶数的常量
  36. while (m2.find()) {
  37. count++;
  38. if (count % 2 == 0) {
  39. // 替换
  40. m2.appendReplacement(sb, "JAVA");
  41. } else {
  42. m2.appendReplacement(sb, "java");
  43. }
  44. }
  45. // 添加尾巴,否则abcdefg不显示
  46. m2.appendTail(sb);
  47. System.out.println(sb);
  48. System.out.println("------------------------------");
  49. // 取符合正则表达式
  50. Pattern p = Pattern.compile("\\d{3,5}[a-z]{2}");
  51. Matcher m3 = p.matcher("123aa-33345bb-234cc-00");
  52. while (m3.find()) {
  53. System.out.print(m3.group() + "\t");
  54. }
  55. System.out.println();
  56. // 使用分组取数字,有几个(就分了几组
  57. // 怎么知道是第几组,规律是(是第几个就是第几组
  58. p = Pattern.compile("(\\d{3,5})([a-z]{2})");
  59. m3 = p.matcher("123aa-33345bb-234cc-00");
  60. while (m3.find()) {
  61. // 只要第一组数字
  62. System.out.print(m3.group(1) + "\t");
  63. }
  64. m3.reset();
  65. System.out.println();
  66. while (m3.find()) {
  67. // 只要第一组字母
  68. System.out.print(m3.group(2) + "\t");
  69. }
  70. }
  71. }
  72. /*
  73. 打印结果:
  74. \d{3,5}
  75. false
  76. true
  77. 0-3
  78. true
  79. ------------------------------
  80. java    JAVA    java    JAVA
  81. ------------------------------
  82. JAVA JAVA JAVAEE hiJAVA abcdefg
  83. ------------------------------
  84. java JAVA javaEE hiJAVA abcdefg
  85. ------------------------------
  86. 123aa   33345bb 234cc
  87. 123 33345   234
  88. aa  bb  cc
  89. */

网页中揪出Email

  1. package com.itlwc;
  2. import java.io.BufferedReader;
  3. import java.io.FileReader;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;
  6. public class Test {
  7. public static void main(String[] args) throws Exception {
  8. FileReader fr = new FileReader("D:\\email.html");
  9. BufferedReader br = new BufferedReader(fr);
  10. String line = "";
  11. while ((line = br.readLine()) != null) {
  12. parse(line);
  13. }
  14. }
  15. private static void parse(String line) {
  16. Pattern p = Pattern.compile("[\\w[.-]]+@[\\w[.-]]+\\.[\\w]+");
  17. Matcher m = p.matcher(line);
  18. while (m.find()) {
  19. System.out.println(m.group());
  20. }
  21. }
  22. }
 
 

java 正则的更多相关文章

  1. Java正则速成秘籍(一)之招式篇

    导读 正则表达式是什么?有什么用? 正则表达式(Regular Expression)是一种文本规则,可以用来校验.查找.替换与规则匹配的文本. 又爱又恨的正则 正则表达式是一个强大的文本匹配工具,但 ...

  2. Java正则速成秘籍(二)之心法篇

    导读 正则表达式是什么?有什么用? 正则表达式(Regular Expression)是一种文本规则,可以用来校验.查找.替换与规则匹配的文本. 又爱又恨的正则 正则表达式是一个强大的文本匹配工具,但 ...

  3. Java正则速成秘籍(三)之见招拆招篇

    导读 正则表达式是什么?有什么用? 正则表达式(Regular Expression)是一种文本规则,可以用来校验.查找.替换与规则匹配的文本. 又爱又恨的正则 正则表达式是一个强大的文本匹配工具,但 ...

  4. java 正则匹配空格字符串 正则表达式截取字符串

    java 正则匹配空格字符串 正则表达式截取字符串 需求:从一堆sql中取出某些特定字符串: 比如配置的sql语句为:"company_code = @cc and project_id = ...

  5. url 中非法字符替换,java 正则替换

    url在传输时不允许的一些字符串,参考自:http://www.ietf.org/rfc/rfc1738.txt 以下字符用java正则替换为"_",一句话搞定: "{& ...

  6. 通用且常用的Java正则匹配工具,用以检查邮箱名、电话号码、用户密码、邮政编码等合法性

    一个通用且常用的Java正则匹配工具,用以检查邮箱名.电话号码.用户密码.邮政编码等合法性. import java.util.regex.Matcher; import java.util.rege ...

  7. java正则匹配

    java正则提取需要用到Matcher类,下面给出案例示例供参考 需要提取车牌号中最后一个数字,比如说:苏A7865提取5,苏A876X提取6import java.util.regex.Matche ...

  8. Java正则表达中Greedy Reluctant Possessive 的区别

    Java正则表达中Greedy Reluctant Possessive 的区别 分类: java2015-01-16 00:28 1280人阅读 评论(9) 收藏 举报 正则表达式Java   目录 ...

  9. java正则 读取html 获取标题/超链接/链接文本/内容

    java正则 读取html 获取标题/超链接/链接文本/内容 参考链接:http://yijianfengvip.blog.163.com/blog/static/175273432201142785 ...

  10. Java正则抓取email

    实现思路 1.使用Java.net.URL对象,绑定网络上某一个网页的地址 2.通过java.net.URL对象的openConnection()方法获得一个HttpConnection对象 3.通过 ...

随机推荐

  1. QT源码剖析之QSS样式表

    1. "QApplication::setStyleSheet()"设置样式表: 1. 创建新的样式表. 2. 设置新的样式. void QApplication::setStyl ...

  2. FileZilla客户端源码解析

    FileZilla客户端源码解析 FTP是TCP/IP协议组的协议,有指令通路和数据通路两条通道.一般来说,FTP标准命令TCP端口号是21,Port方式数据传输端口是20. FileZilla作为p ...

  3. linux下安装LoadRunner LoadGenerator

    root用户登录 关闭防火墙: setenforce 0 /etc/init.d/iptables stop 先安装一个rpm包,compat-libstdc++-33-3.2.3-61.i386.r ...

  4. sqlserver2012评估期已过问题处理

    于之前安装sqlserver2012忘记输入序列号,现在出现评估期已过的问题,网上忙活半天,才解决,发现网上叙述都很凌乱,而且只有大意,新手很难操作,所以把我操作的过程分享给大家 步骤阅读   百度经 ...

  5. 第三天 函数 三元运算 lambda表达式 内置函数 文件操作

    面向过程: 直接一行一行写代码,遇到重复的内容复制黏贴. 不利于代码阅读 代码没有复用 面向对象 将代码块定义为函数,以后直接调用函数 增强了复用性 函数的定义方法 def 函数名(传递参数): 函数 ...

  6. Acer VN7 Win10小键盘修改

    由于 Home End 正常位置太远, NumberLock 容易误按, 故设置win10 键位映射如下图

  7. #Eureka 客户端和服务端间的交互

    Eureka 服务器客户端相关配置 1.建立eureka服务器 只需要使用@EnableEurekaServer注解就可以让应用变为Eureka服务器,这是因为spring boot封装了Eureka ...

  8. linux搭建apache服务并修改默认路径

    该篇文章主要讲解如何在linux服务器上搭建apache服务器,并修改指定的apache路径到自定义路径下 一:检查服务器上是否已安装apache,停止并卸载系统自带apache服务 命令为:rpm ...

  9. python网络编程 — HTTP客户端

    A simple http client. It gets the contents of special webserver page and print it.(Default path is & ...

  10. toString--->转字符串

    因为它是Object里面已经有了的方法,而所有类都是继承Object,所以“所有对象都有这个方法”.它通常只是为了方便输出,比如System.out.println(xx),括号里面的“xx”如果不是 ...