Explain Codes LogoExplain Codes Logo

Java: method to get position of a match in a String?

java
string-manipulation
regex-patterns
performance-optimization
Nikita BarsukovbyNikita Barsukov·Feb 26, 2025
TLDR

Finding a match's position in a String is a piece of cake using indexOf:

String str = "Example"; int pos = str.indexOf("am"); // pos will be 2, unless the String runs away

In case there's no match, be prepared for a -1:

int pos = str.indexOf("cake"); // pos will be -1, no cake in the string, sadly.

If you're dealing with more instances of the match, this loop is your friend:

int startIndex = 0; while ((startIndex = str.indexOf("am", startIndex)) != -1) { System.out.println(startIndex); // StartIndex, the index that starts something new, every loop cycle! startIndex += "am".length(); }

Catch them all: getting multiple match positions

In a world full of multiple occurrences of your match, the indexOf method turns into a Poké ball, capturing all match positions:

int startIndex = 0; while ((startIndex = str.indexOf("am", startIndex)) != -1) { int endIndex = startIndex + "am".length(); System.out.println("Match at: " + startIndex + " to " + (endIndex - 1)); // endIndex, the unsung hero who takes one for the team by being one less startIndex = endIndex; // Don't forget to treat endIndex equal, it's not all about 'start'! }

Regex: the advanced match catcher

For the Detective Pikachus out there dealing with complex patterns, say hello to Pattern and Matcher classes:

Pattern pattern = Pattern.compile("am"); Matcher matcher = pattern.matcher("Example"); while (matcher.find()) { System.out.println("Match at: " + matcher.start()); // matcher.start(), because even matchers have a starting point in life }

find()is the search light, and start() is the treasure chest's X mark. To catch the No Man's Land after the match, end() is your pick!

Edge cases and efficiency guide

Starting from the mid-string

fromIndex with indexOf is your go-to trick when your string is as large as the Great Wall of China:

int fromIndex = 3; int pos = str.indexOf("am", fromIndex); // pos, starting from 3, discovers newfound freedom and speed

From the end, with lastIndexOf

lastIndexOfcomes into play when you're feeling adventurous and want to begin your search from the end:

int posFromEnd = str.lastIndexOf("am"); // posFromEnd turns out to be 2, `am` was closer than we thought!

indexOf vs. regex: the efficient player

Where indexOf outshines with its quick footwork in simple matching, regex pulls up a fight with intricate complex patterns. Choose your warrior wisely!

The dos and don'ts

  • Beware of off-by-one errors: Crossing the boundary won't transport you to Stranger Things!
  • Refresh index positions: Unless you enjoy Groundhog Day, keep updating indices in loops.
  • Unleash indexOf: Oh simple sub-string searches, indexOf is thy answer! No need to dive into regex waters.