Java中如何使用字符串中特定单词的正则表达式查找最后一个索引?

要在 Java 中使用正则表达式查找字符串中特定单词的最后一个索引,您可以使用 Matcher 类以及捕获所需单词的正则表达式。

Java 程序使用字符串中特定单词的正则表达式来查找最后一个索引
下面是使用字符串中特定单词的正则表达式的最后一个索引的实现:

// Java Program to Find last index 
// Using the Regex of a Particular Word in a String 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

// Driver Class 
public class LastIndexOfWordUsingRegex { 
    
// Main Function 
    public static void main(String[] args) { 
        String inputString =
"This is a sample sentence with a particular word. Another occurrence of the word."

        
// 指定要查找的单词 ;
        String wordToFind =
"word"

        
// 使用单词和输入结束锚点创建模式 
        String regex =
"\\b" + Pattern.quote(wordToFind) + "\\b"
        Pattern pattern = Pattern.compile(regex); 

        
// 为输入字符串创建匹配器 ;
        Matcher matcher = pattern.matcher(inputString); 

        
// 查找最后出现的单词 ;
        int lastIndex = -1; 
        while (matcher.find()) { 
            lastIndex = matcher.start(); 
        } 

        
// 打印最后一个索引,或在未找到单词时显示 ;
        if (lastIndex != -1) { 
            System.out.println(
"Last index of '" + wordToFind + "': " + lastIndex); 
        } else
            System.out.println(
"'" + wordToFind + "' not found in the string."); 
        } 
    } 


  • 正则表达式 \\b 用于表示单词边界。
  • Pattern.quote(wordToFind) 用于转义单词中的任何特殊字符。
  • 输入结束锚 $ 用于确保匹配发生在输入的末尾。
  • Matcher 使用 find() 迭代输入字符串,每次找到匹配项时更新 lastIndex。