Java正则表达式:匹配和提取字符串

引言

正则表达式是一种强大的文本匹配工具,它可以帮助我们在字符串中进行复杂的模式匹配操作。在Java中,可以使用java.util.regex包来操作正则表达式。本文将介绍如何使用Java提取字符串中匹配的内容,以及一些常用的正则表达式匹配模式。

正则表达式基础

正则表达式是一种用于描述文本模式的字符串,并用于匹配、查找和替换字符串。它由普通字符和特殊字符组成,特殊字符具有特殊的含义。

在Java中,可以使用PatternMatcher类来进行正则表达式的匹配和提取操作。Pattern是一个正则表达式的编译表示,Matcher则是对输入字符串进行匹配操作的引擎。

以下是一些常用的正则表达式特殊字符及其含义:

  • .: 匹配除换行符以外的任意字符。
  • *: 匹配前面的元素零次或多次。
  • +: 匹配前面的元素一次或多次。
  • ?: 匹配前面的元素零次或一次。
  • []: 匹配中括号内的任意字符。
  • |: 匹配两个或多个正则表达式之一。
  • \: 转义字符,用于匹配特殊字符本身。
  • ^: 匹配字符串的开头。
  • $: 匹配字符串的结尾。

使用正则表达式匹配字符串

以下是一个使用正则表达式匹配字符串的示例代码:

import java.util.regex.*;

public class RegexExample {
    public static void main(String[] args) {
        String input = "Hello, world! This is a test string.";

        // 定义正则表达式模式
        String pattern = "test.*";

        // 编译正则表达式
        Pattern compiledPattern = Pattern.compile(pattern);

        // 创建Matcher对象
        Matcher matcher = compiledPattern.matcher(input);

        // 查找匹配的字符串
        if (matcher.find()) {
            System.out.println("Found match: " + matcher.group());
        } else {
            System.out.println("No match found.");
        }
    }
}

上述代码中,首先定义了一个输入字符串input和一个正则表达式模式pattern。然后,使用Pattern.compile()方法将正则表达式编译为Pattern对象。接下来,创建Matcher对象,并使用find()方法查找匹配的字符串。如果找到了匹配的字符串,可以使用group()方法获取匹配的字符串。

在上述示例中,正则表达式模式test.*表示匹配以test开头,后面跟着任意字符的字符串。因此,程序输出为Found match: test string.

提取匹配的字符串

除了查找匹配的字符串,还可以提取匹配的内容。在正则表达式中,可以使用括号()将需要提取的部分括起来,然后使用group()方法获取提取的内容。

以下是一个提取匹配内容的示例代码:

import java.util.regex.*;

public class RegexExample {
    public static void main(String[] args) {
        String input = "John Doe (john.doe@example.com), Jane Smith (jane.smith@example.com)";

        // 定义正则表达式模式
        String pattern = "\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b";

        // 编译正则表达式
        Pattern compiledPattern = Pattern.compile(pattern);

        // 创建Matcher对象
        Matcher matcher = compiledPattern.matcher(input);

        // 提取匹配的字符串
        while (matcher.find()) {
            System.out.println("Email: " + matcher.group());
        }
    }
}

上述代码中,正则表达式模式\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b表示匹配一个合法的电子邮件地址。程序输出为:

Email: john.doe@example.com
Email: jane.smith@example.com