• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Java正则表达式工具的使用

武飞扬头像
Rex Chou
帮助1

概述

在java中,提供了一些跟正则表达式有关的工具类,例如String、Pattern、Matcher、PatternSyntaxException等等,可以进行丰富的与正则表达式有关的操作,本文便依据功能分类来对这些功能的使用进行详细讲解。

匹配功能

String的matches方法

boolean matches(String regex),求表达式和字符串能否完全匹配。

public static void main(String[] args) {
    String str1 = "abc123ABC";
    boolean isMatch1 = str1.matches("[0-9] ");
    System.out.println(isMatch1); // 输出结果为:false

    String str2 = "abc123ABC";
    boolean isMatch2 = str2.matches("[a-z] [0-9] [A-Z] ");
    System.out.println(isMatch2); // 输出结果为:true
}

Pattern的matches方法

static boolean matches(String regex, CharSequence input),求表达式和字符串能否完全匹配。

public static void main(String[] args) {
    boolean isMatch1 = Pattern.matches("[a-c] ", "abc123ABC");
    System.out.println(isMatch1); // 输出结果为:false

    boolean isMatch2 = Pattern.matches("[a-z] [0-9] [A-Z] ", "abc123ABC");
    System.out.println(isMatch2); // 输出结果为:true
}

Matcher的matches方法

boolean matches(),求表达式和字符串能否完全匹配。

public static void main(String[] args) {
    Pattern pattern1 = Pattern.compile("[a-z] ");
    Matcher matcher1 = pattern1.matcher("abc123ABC");
    System.out.println(matcher1.matches()); // 输出结果为:false

    Pattern pattern2 = Pattern.compile("[a-z] [0-9] [A-Z] ");
    Matcher matcher2 = pattern2.matcher("abc123ABC");
    System.out.println(matcher2.matches()); // 输出结果为:true
}

查找功能

lookingAt方法

boolean lookingAt(),求表达式能否匹配到字符串的开头部分。

public static void main(String[] args) {
    Pattern pattern1 = Pattern.compile("[0-9] ");
    Matcher matcher1 = pattern1.matcher("abc123ABC");
    System.out.println(matcher1.lookingAt()); // 输出结果为:false

    Pattern pattern2 = Pattern.compile("[a-z] ");
    Matcher matcher2 = pattern2.matcher("abc123ABC");
    System.out.println(matcher2.lookingAt()); // 输出结果为:true
}

find方法

boolean find(),求表达式能否匹配到字符串中的部分内容,它是从字符串的头部开始往后查找的,每调用一次find方法,会告诉你能否找到下一个符合表达式的内容。

public static void main(String[] args) {
    Pattern pattern = Pattern.compile("[a-c] ");
    Matcher matcher = pattern.matcher("abc123abcABCabc");
    
    int count = 0;
    while (matcher.find()){
        count  ;
    }
    System.out.println(count); // 输出结果为:3
}

补充:boolean find(int start),它是从字符串中你希望的位置开始往后查找的。

分割功能

split方法

String[] split(CharSequence input),让表达式匹配到的内容作为分割点,把字符串分割后存到一个新的字符串数组中返回。

public static void main(String[] args) {
    Pattern pattern = Pattern.compile("[a-c] ");
    String[] array = pattern.split("abc123abcABCabc");
    System.out.println(Arrays.toString(array)); // 输出结果为:[, 123, ABC]
}

注意:如果表达式在字符串的开头能匹配到,则输出的字符串数组的第一个元素是无内容的。

分组功能

public static void main(String[] args) {
    Pattern pattern = Pattern.compile("([a-z] ([0-9] ))[A-Z] ");
    Matcher matcher = pattern.matcher("#@!abc123ABC%&=");

    int count = matcher.groupCount();
    System.out.println("count:"   count);

    if (matcher.find()) {
        for (int i = 0; i <= count; i  ) {
            System.out.println(i   ":"   matcher.group(i));
        }
    }
    
	// 输出结果为:
	/*
	count:2
	0:abc123ABC
	1:abc123
	2:123
	*/
}
学新通
  • 在表达式中,是用分组小括号来进行分组的。
  • 整个表达式也算作一个组,对应的索引号为0。
  • 分组小括号可以嵌套使用,例如 ((a)b) 存在两个组,分别为 a 和 ab 。
  • Matcher的groupCount方法,会对表达式进行分析,然后告诉你表达式中有多少对分组小括号。
  • Matcher的group方法,会根据索引获取对应的组的内容。

start方法和end方法

public static void main(String[] args) {
    Pattern pattern = Pattern.compile("[a-c] ");
    Matcher matcher = pattern.matcher("abc123abcABCabc");
    while (matcher.find()) {
        System.out.println("在字符串的"   matcher.start()   "到"   matcher.end()   "的位置配置到一个");
    }
    // 输出结果为:
    /*
    在字符串的0到3的位置配置到一个
    在字符串的6到9的位置配置到一个
    在字符串的12到15的位置配置到一个
    * */
}

替换功能

replaceFirst方法

String replaceFirst(String replacement),替换掉字符串中第一个符合表达式的内容,返回新的字符串。

public static void main(String[] args) {
    Pattern pattern = Pattern.compile("[a-c] ");
    Matcher matcher = pattern.matcher("abc123abcABCabc");

    String str = matcher.replaceFirst("###");
    System.out.println(str); // 输出结果为:###123abcABCabc
}

replaceAll方法

String replaceAll(String replacement),替换掉字符串中每个符合表达式的内容,返回新的字符串。

public static void main(String[] args) {
    Pattern pattern = Pattern.compile("[a-c] ");
    Matcher matcher = pattern.matcher("abc123abcABCabc");

    String str = matcher.replaceAll("###");
    System.out.println(str); // 输出结果为:###123###ABC###
}

appendReplacement方法和appendTail方法

这两个方法是一起协同完成替换功能的,替换掉字符串中每个符合表达式的内容,最终结果会存到StringBuffer对象中。

public static void main(String[] args) {
    Pattern pattern = Pattern.compile("[a-c] ");
    Matcher matcher = pattern.matcher("abc123abcABCabc");

    String str = "###";
    StringBuffer sb = new StringBuffer();

    while (matcher.find()) {
        matcher.appendReplacement(sb, str);
    }
    matcher.appendTail(sb);

    System.out.println(sb); // 输出结果为:###123###ABC###
}

异常

为了方便检测上文所使用的功能在运行过程中可能会发生的未知错误,可使用PatternSyntaxException异常类。

public static void main(String[] args) {
    try {
        boolean isMatch1 = Pattern.matches("[a-c] ", "123ABC");
        System.out.println(isMatch1);
        
    } catch (PatternSyntaxException e) {
        System.out.println("与错误有关的描述:"   e.getDescription());
        System.out.println("与错误有关的索引:"   e.getIndex());
        System.out.println("与错误有关的Pattern:"   e.getPattern());
        System.out.println("与错误有关的所有信息:"   e.getMessage());
    }
}

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgeijij
系列文章
更多 icon
同类精品
更多 icon
继续加载