使用正则表达式查找单词出现的 Java 程序

Java 的正则表达式(或称正则表达式)可让您进行高级文本操作和匹配。正则表达式提供了一种方便的方法来搜索文本中出现的术语。在本文中,我们将学习使用正则表达式查找单词的每次出现。

使用正则表达式查找单词出现的程序
主要思想是使用Java的java.util.regex库,即Pattern和Matcher类。您可以使用正则表达式创建与特定单词或字符序列匹配的模式。 Matcher 类帮助在提供的文本中定位模式的实例,而 Pattern 类则组装正则表达式模式。

// Java program to find occurrences of a 
// specific word in a given text using regular expressions 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

// Class definition for WordOccurrencesExample 
public class WordOccurrencesExample { 
    
// Main method 
    public static void main(String[] args) { 
        
// Create a sample text 
        String text =
"Java is a versatile programming language. Java is widely used in software development."

        
// Define the word to find occurrences 
        String wordToFind =
"Java"

        
// 使用单词  创建一个 regex 模式;
        Pattern pattern = Pattern.compile(
"\\b" + wordToFind + "\\b", Pattern.CASE_INSENSITIVE); 

        
// Create a matcher for the text 
        Matcher matcher = pattern.matcher(text); 

        
// Find and display every occurrence of the word 
        System.out.println(
"Occurrences of the word '" + wordToFind + "':"); 
        while (matcher.find()) { 
            System.out.println(
"Found at index " + matcher.start() + " - " + matcher.group()); 
        } 
    } 

上述程序的解释:

  • 创建示例文本
  • 定义单词以查找出现的次数
  • 使用单词创建正则表达式模式
  • 为文本创建匹配器
  • 查找并显示该单词的每次出现