Ritesh Singh
Ritesh Singh

Reputation: 223

Check for a Substring after a particular occurrence of string which is separated by dots

I have a string with dots. I want to get a particular substring after occurrence of word

entity

that is for example

String givenStr = "com.web.rit.entity.TestName.create";
output - TestName

String givenStr = "com.web.rit.entity.TestName2.update";
output - TestName2

So as explained above I have to extract substring after the string entity from the given string. Can anyone please help? (I am using java to do it).

Upvotes: 0

Views: 137

Answers (3)

Andy Brown
Andy Brown

Reputation: 12999

Here's a streams solution (Java 9 minimum requirement):

Optional<String> value = Arrays
     .stream("com.web.rit.entity.TestName.create".split("\\."))
     .dropWhile(s -> !s.equals("entity"))
     .skip(1)
     .findFirst();

System.out.println(value.orElse("not found"));

Upvotes: 1

Melron
Melron

Reputation: 579

You can use 2 splits.

String word = givenStr.split("entity.")[1].split("\\.")[0];

Explaination:

Assuming the givenStr is "com.web.rit.entity.TestName.create"

givenStr.split("entity.")[1] // Get the sentence after the entity.

"TestName.create"

split("\\.")[0] // Get the string before the '.'

TestName

Upvotes: 2

Elikill58
Elikill58

Reputation: 4908

You can do something like this :

String givenStr = "com.web.rit.entity.TestName.create"; // begin str
String wording = "entity"; // looking for begin
String[] splitted = givenStr.split("\\."); // get all args
for(int i = 0; i < splitted.length; i++) {
    if(splitted[i].equalsIgnoreCase(wording)) { // checking if it's what is required
        System.out.println("Output: " + splitted[i + 1]); // should not be the last item, else you will get error. You can add if arg before to fix it
        return;
   }
}

Upvotes: 1

Related Questions