To find the last index of a particular word in a string using regular expressions in Java, you can use the Matcher class along with a regular expression that captures the desired word.
Java Program to last index Using the Regex of a Particular Word in a String
Below is the implementation of the last index Using the Regex of a Particular Word in a String:
// 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.";
// Specify the word you want to find
String wordToFind = "word";
// Create a pattern with the word and the end-of-input anchor
String regex = "\\b" + Pattern.quote(wordToFind) + "\\b";
Pattern pattern = Pattern.compile(regex);
// Create a matcher for the input string
Matcher matcher = pattern.matcher(inputString);
// Find the last occurrence of the word
int lastIndex = -1;
while (matcher.find()) {
lastIndex = matcher.start();
}
// Print the last index or indicate if the word is not found
if (lastIndex != -1) {
System.out.println("Last index of '" + wordToFind + "': " + lastIndex);
} else {
System.out.println("'" + wordToFind + "' not found in the string.");
}
}
}
Output:
Last index of 'word': 76Explanation of the above Program:
- The regular expression \\b is used to denote a word boundary.
- Pattern.quote(wordToFind) is used to escape any special characters in the word.
- The end-of-input anchor $ is used to ensure that the match occurs at the end of the input.
- The Matcher iterates through the input string using find(), updating the lastIndex each time a match is found.
Note: This approach assumes that you want to match whole words. If you want to find occurrences within other words, you may need to adjust the regular expression accordingly.