在由点分隔的特定字符串出现后检查子字符串

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

我有一个带点的字符串。我想在出现 word

后得到一个特定的子串

entity

例如

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

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

所以如上所述,我必须从给定的字符串中提取字符串 entity 之后的子字符串。有人可以帮忙吗? (我正在使用 java 来做)。

您可以使用 2 个拆分。

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

解释:

假设 givenStr 是“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 '.'

测试名称

你可以这样做:

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;
   }
}

这是一个流解决方案(Java 9 最低要求):

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"));