Skip to content

Java RegEx – indexOf & lastIndexOf substring

Java RegEx – indexOf & lastIndexOf substring example shows how to find an index of a substring in a string using regular expression pattern instead of indexOf or lastIndexOf methods of the String class.

How to find the index of a substring using regex in Java?

The Java String class provides overloaded indexOf methods to find the index of a specific substring or subsequence within given string content. These indexOf methods are overloaded for String as well char data types.

However, many times some use case requires us to search for a complicated pattern inside of the string content instead of a simple substring. The indexOf method of the String class does not accept a regex pattern. For example, you want to find an index of a number in the string, but you do not know the exact number you are looking for. It could be 1, or 100, or 1000. In this case, the indexOf method of the String class cannot be used.

In that case, we can use the Pattern and Matcher class. Using the find method and start method of the Matcher class, we can implement our own indexOf method that accepts a regex pattern as given below.

Output

As you can see from the output, our indexOf method found the number in a string at index 19. The same code can be written in a very compact form as given below.

Important Note:

The indexOf methods of the String class are more efficient in terms of performance as compared to our version of the method using the regex pattern. For normal substring matches, using them over the pattern version is recommended.

How to find the last index of a substring using regex in Java?

Finding the last index of a substring is a little bit tricky as compared to the first index. One way is to use a while loop to iterate through all the matches and then use the last match to get the last index as given below.

Output

As you can see from the output, this time our code found the index of the last number i.e. number 100 in string content.

If you want to learn more about regex in Java, visit regex tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.