Search code examples
javastringsubstring

Java - How to extract a substring from start until the end of a particular word in a string?


Input string:

String sentence = "I am an Administrator of my building";

Desired Output String = "I am an Administrator"

Pattern for extracting the substring: Get the substring starting from the beginning of the 'sentence' string and until the end of the word 'Administrator'.

I could get the endIndex of 'Administrator' and then use substring(int beginIndex, int endIndex)

Not sure if this is the most efficient way to do it. What would the efficient or short way to achieve this?


Solution

  • Regex to the rescue:

    String start = sentence.replaceAll("(?<=Administrator).*", "");
    

    This works by matching everything after Administrator and replacing it with nothing (effectively "deleting" it).

    The key part of the regex is the look behind (?<=Administrator), which matches immediately after Administrator - between the r and the space.