How to find the last index using regex of a particular word in a String?
Last Updated :
25 Jan, 2024
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
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LastIndexOfWordUsingRegex {
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." );
}
}
}
|
Output:
Last index of 'word': 76
Explanation 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.
Share your thoughts in the comments
Please Login to comment...