srh snl
srh snl

Reputation: 807

Find the last index of the first match in Java

Lets say I have this string

String s ="stackjomvammssastackvmlmvlrstack"

And I want to find the last index of the first match of the substring "stack" which is (index=)4 in my example.

How will I do that?

Here's what I have done so far

    Matcher m = pattern.matcher(s);
    int i=0;
    while (m.find())
    {    
        System.out.println(m.start());
        System.out.println(m.end());
    }

But that displays the last index of the last match.

Upvotes: 0

Views: 3405

Answers (7)

Civa
Civa

Reputation: 2176

im edited my previous answer

  String s ="stackjomvammssastackvmlmvlrstack";      
  String pattern = "stack";

Matcher m = pattern.matcher(s);
int i=0;
while (m.find())
{    
    System.out.println(m.start());
    System.out.println(m.start()+m.length());
}

Upvotes: -1

Kent
Kent

Reputation: 195289

try this code:

if (m.find())
        System.out.println(m.end() - 1);

from java doc of Matcher.end():

Returns the offset after the last character matched. 

Upvotes: 1

assylias
assylias

Reputation: 328923

You can simply find the position of the word and add its length:

String s = "stackjomvammssastackvmlmvlrstack";
String match = "stack";
int start = s.indexOf(match);
int end = (start + match.length() - 1);
System.out.println(match + " found at index " + start);
System.out.println("Index of last character of first match is " + end);

If you need to use a regex, your code is close to the solution - you could do this:

String s = "stackjomvammssastackvmlmvlrstack";
String match = "s.*?k";
Matcher m = Pattern.compile(match).matcher(s);
if (m.find()) {
    System.out.println(m.end() - 1);
}

Upvotes: 6

Bob Flannigon
Bob Flannigon

Reputation: 1294

String s = "stackjomvammssastackvmlmvlrstack";

String stack = "stack"; int index = s.indexOf(stack) + stack.length();

Upvotes: 0

user1907906
user1907906

Reputation:

final String input = "stackjomvammssastackvmlmvlrstack";
final String stack = "stack";
int start = input.indexOf(stack);
int end = start + stack.length() - 1;

Upvotes: 0

gpunto
gpunto

Reputation: 2852

This way?

String s ="stackjomvammssastackvmlmvlrstack";
String word = "stack";
int index = s.indexOf(word) + word.length() - 1;

Upvotes: 0

Gaston Claret
Gaston Claret

Reputation: 998

If I understood your question right, you are trying to find the first match of "stack", and then get the last index....

You can accomplish this by doing:

string toFind = "stack";
int firstOccurance = s.indexOf(toFind); (being s the word you posted above)
int whatYourLooking = firstOccurance + toFind.length() - 1; 

Hope it helps! ;)

Upvotes: 0

Related Questions