Menu
CoddyTech

使用 Regex 进行模式匹配

本课属于 Coddy Java 学习旅程的“逻辑与流程”单元。第 47 课,共 59 课。

Pattern 和 Matcher 类为你在 Java 中进行正则表达式操作提供了强大的工具。首先,我们来了解如何使用它们:

使用 Pattern.compile() 创建一个 pattern:

Pattern pattern = Pattern.compile("cat");
// 创建一个用于查找 "cat" 的模式

为你的文本创建一个 matcher:

String text = "The cat and dog";
Matcher matcher = pattern.matcher(text);
// 为文本创建匹配器

现在,你可以使用 matcher.find() 查找匹配项:

while (matcher.find()) {
   System.out.println("Found at: " + matcher.start());
}

运行上面的代码后,输出为:Found at: 4

了解这些方法:

  • matcher.find() - 在文本中搜索下一个匹配项
    • 如果找到匹配项,则返回 true
    • 如果没有更多匹配项,则返回 false
    • 这就是我们在 while 循环中使用它的原因:查找所有匹配项
  • matcher.start() - 返回 find() 找到的上一个匹配项的起始索引(位置)
    • 在我们的示例中,"cat" 在 "The cat and dog" 中从索引 4 开始
    • 必须在 find() 成功后调用

包含多个匹配项的示例:

Pattern pattern = Pattern.compile("cat");
Matcher matcher = pattern.matcher("cat and cat");
while (matcher.find()) {
   System.out.println("Found at: " + matcher.start());
}
// 输出:
// Found at: 0
// Found at: 8
challenge icon

挑战

简单

创建一个名为 findWords 的方法,它接受两个参数:

  1. 要在其中搜索的字符串(text)
  2. 要查找的字符串(word)

该方法应:

  1. 使用 Pattern 和 Matcher 查找该单词的所有匹配项
  2. 返回一个字符串,其中包含找到该单词的位置
  3. 位置之间用空格分隔

返回的消息应为:

  • 如果任何输入为 null:返回 "Invalid input"
  • 如果未找到该单词:返回 "Not found"
  • 如果找到:返回位置(例如,"4 10 15")

亲手试试

import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Main {
    public static String findWords(String text, String word) {
        // 在这里编写你的代码
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String text = scanner.nextLine();
        String word = scanner.nextLine();
        
        if (text.equals("null")) text = null;
        if (word.equals("null")) word = null;
        
        System.out.println(findWords(text, word));
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

逻辑与流程中的所有课

自己练习: Java 在线编译器

用你自己的文本测试正则: 正则表达式测试器