Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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‘.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 Administratorbetween the r and the space.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading