2

For example, I have a string like this:

String string = "Some random string 1aaa5 some random string";

And I want to get start and end index of a substring "1aaa5" or similar, matched by a regex pattern:

Pattern pattern = Pattern.compile("\\d\\w+\\d");

In this case, result would be 20 and 24, for start and end respectively.

Is there a way to do this in Java?

Goran Jovic
  • 9,418
  • 3
  • 43
  • 75

1 Answers1

4
Matcher matcher = pattern.matcher(string)
if (matcher.find()) {
    start = matcher.start()
    end = matcher.end()
    text = matcher.group()
}
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561