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).
CodePudding user response:
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;
}
}
CodePudding user response:
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
CodePudding user response:
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"));