Reputation: 45
In Java the Matcher class has the method find(int start)
which looks for the first match after the index 'start'. You can retrieve information about this match using other methods of the class. I want to get instead the *last match before the index 'start' i.e. the previous match instead of the next mathc.
My question is: Is there a better approach than to iterate through the whole string finding all the matches until you reach that index?
Here's an example:
Let's say I have an input:
"Hey It's John Smith here. Hello my name is John Smith . Hello again, my name's still John Smith",
and a pattern:
"John\\s"
If my index is the bold period (53), it's very easy to find the next "John " with find(), but I want to be able to match the previous bold "John ". I want to get it's start and end indices (43, 47) so I can highlight this piece of text and bring the cursor to the end index. I want to do this at any point i.e. get the previous match from that cursor position and obtain it's start and end indices.
Here is some code which might represent:
String input = "Hey It's John Smith here. Hello my name is John Smith. Hello again, my name's still John Smith";
String pattern = "John\\s";
Matcher matcher = Pattern.compile(pattern).matcher(input);
...
matcher.find(53);
// get some information about the result
This gets the next "John " but I want to find the bold "John " instead, I have to do a loop which finds a match and then checks if the start of the match if above 53, if it is, then use the previous match.
For Background: The purpose for this is to implement ctrl F functionality so that you can go to a previous match when you search for something. I'm not sure if this is a good way to do it but I guess it is a learning experience.
Upvotes: 1
Views: 99
Reputation: 2546
Your question is not very clear as mentioned in comments but as @sorifiend said you can use substring method:
String substring = input.substring(0,53);
And then find the last occurrence in the substring:
matcher.group(matcher.groupCount());
Complete solutions:
public static void main(String[] args) {
String input = "Hey It's John Smith here. Hello my name is John Smith. Hello again, my name's still John Smith";
String substring = input.substring(0,53);
String pattern = "John\\s";
Matcher matcher = Pattern.compile(pattern).matcher(substring);
System.out.println(matcher.group(matcher.groupCount()));
}
Upvotes: 1