Java正则表达式

一、String中使用正则表达式的方法

  • matches()
    • 匹配 public boolean matches(String regex)
  • splits()
    • 拆分 public String[] splits(String regex)
    • 拆分 public String[] splits(String regex, int limit) 限制最多拆分几次
  • replaceAll()
    • 替换所有 public String replaceAll(String regex, String replacement)
  • replaceFirst()
    • 替换一次 public String replaceFirst(String regex, String replacement)

应用实例1:

String str = "GET /index.html HTTP/1.1";
String arr[] = str.split(" +");
for(String s :arr){
    System.out.println(s);
}

结果:

image

应用实例2:

String str = "lzb_box@126.com";
String reg = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-+]\\w+)*";
System.out.println(str.replaceAll(reg, "EMAIL"));

结果:

image

二、使用正则表达式库Pattern和Matcher

两种惯常使用方式

//惯常方式一
 Pattern p = Pattern.compile("a*b");
 Matcher m = p.matcher("aaaaab");
 boolean b = m.matches();

//惯常方式二:仅使用一次正则表达式
boolean b = Pattern.matches("a*b", "aaaaab");
  • Matcher.find() 查询
  • Matcher.group() 提取
  • Pattern.split() 拆分
  • Matcher.replaceAll()替换
//实例group
String reg = ".+\\\\(.+)";
String str = "c:\\dir1\\dir2\\name.txt";
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher(str);
boolean rs = m.matches();
if(rs){
    for(int i=0; i<m.groupCount(); i++){
        System.out.println(m.group(i));
    }
}

三、关键知识点

  1. 正则表达式的匹配字符分类:
    1. 普通字符
    2. 非打印字符
    3. 特殊字符
    4. 次数限定符
    5. 定位符
    6. 选择与分组
    7. 向后引用
  2. 正则表达式匹配规则
    1. 基本模式匹配
    2. 字符族匹配
    3. 重复出现匹配
    4. 贪婪与非贪婪
    5. 反向引用
    6. 欲搜索与懒惰搜索
  3. Java中能够使用正则匹配的类
    1. String 功能: 匹配、拆分、替换
    2. Pattern和Matcher功能: 查找、提取、分隔、替换

四、常用正则举例

  • /^[1-9]\d*|0$/  非负整数
  • /^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*)|0?\.0+|0$/ 浮点数
  • /^[A-Za-z]+$/ 英文字母
  • /^[A-Za-z0-9]+$/ 字母和数字
  • /^\w+$/ 字母、数字或下划线
  • /[\u4e00-\u9fa5] 匹配中文字符
  • /\n\s*\r/ 空白行
  • /^\s*|\s*$/ 首尾空白
原文地址:https://www.cnblogs.com/huntdream/p/3061857.html