java:检索以特定字符串开头和结尾的字符串的一部分

标签 java string

这是程序,我有一个字符串 strLineText ,我需要从中提取包含 target 的单词。

例如。在字符串“带有 IWANTTHISABC-123 及更多内容的随机字符串” 中,我需要提取 IWANTTHISABC-123。同样,如果字符串是“带有 IWANTTHISBBC-001 的随机字符串”,我需要提取“IWANTTHISBBC-001”。前缀是固定的

我已尝试使用 substring() (Method1) 但该逻辑不适用于以此目标单词结尾的字符串即没有输出任何内容

我尝试了 split() (Method2),它适用于所有四种组合。

你能帮我实现对所有四种组合使用 substring() (Method1)

public static void main(String[] args) throws IOException {

    String target = "IWANTTHIS";

    //Four possible inputs
    String strLineText = "random string with IWANTTHISABC-123 and more";   //works
    String strLineText = "IWANTTHISCBC-45601 and more";                    //works
    String strLineText = "IWANTTHISEBC-1";                                 //doesn't work
    String strLineText = "random string with IWANTTHISKBC-55545";          //doesn't work

    //Method1
    System.out.println("O/P 1:" + strLineText.substring(strLineText.indexOf(target), 
            strLineText.indexOf(target) + strLineText.substring(strLineText.indexOf(target)).indexOf(" ") + 1).trim());

    //Method2
    for (String s : strLineText.split(" "))
        if (s.contains(target))
            System.out.println("O/P 2:" + s.trim());
}

最佳答案

我认为这非常简单,您只需要从开始索引开始计算结束索引即可。这是适用于所有情况的代码片段。

int begin = strLineText.indexOf(target);
int end = strLineText.indexOf(" ", begin);
if(end == -1) end = strLineText.length();

System.out.println(strLineText.substring(begin, end));

关于java:检索以特定字符串开头和结尾的字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59340309/

相关文章:

javascript - 如何在我的 View 中打印 JavaScript 代码?

javascript - 如何在自定义JQuery中添加日期原始/后缀?

java - 如何自动生成给定的 String 数组?

java - 为什么这个正则表达式没有给出预期的输出?

Java : How to set the flag value in a array loop

java - 当子实体与父实体之间存在一对一的 JPA 关系时,是否可以将子实体与父实体一起保留?

java.lang.NoClassDefFoundError :

Python repr 字符串带真正的换行符

java - JFreeChart 在模态 JDialog 中不可见?

java - 如何在maven eclipse项目中使用cplex.jar?