代码之家  ›  专栏  ›  技术社区  ›  dimitri08

如何通过删除可能出现在任何地方的指定单词来从字符串中提取子字符串?

  •  2
  • dimitri08  · 技术社区  · 1 年前

    例如,我有一个字符串, "John Doe" ,其中一个单词是已知关键字,另一个是我需要提取的剩余部分。给定一个字符串,如 “无名氏” ,我知道关键字,例如。, "Doe" ,我想提取另一个词,“约翰”。

    我最初尝试了这种方法:

    String input = "John Doe";
    String keyword = "Doe";
    String result = input.replace(keyword, "").trim();
    

    如果 keyword 位于字符串末尾。但是,它不处理以下情况 关键字 可能在开始或在中间的某个地方。例如,如果输入为 "Doe John" 或者如果关键字是另一个单词的一部分,比如 "Johnathan" ,它失败了。假使 "Johnathan Doe" ,使用 "John" 因为关键字错误地返回“athan Doe”。

    我需要一种方法,当关键字已知时,无论其在字符串中的位置如何,都能可靠地提取字符串的剩余部分,并将关键字视为一个完整的单词。

    我也试过这个:

    String input = "John Doe";
    String receiver = "Doe";
    String[] parts = input.split("\\b" + receiver + "\\b");
    String result = "";
    if (parts.length > 1 && !parts[1].trim().isEmpty()) {
        sender = parts[1].trim();
    }
    else if (parts.length > 0 && !parts[0].trim().isEmpty()) {
        sender = parts[0].trim();
    }   
    

    但还有很长的路要走。当然,有一种更短的方法可以做到这一点

    2 回复  |  直到 1 年前
        1
  •  0
  •   WJS    1 年前

    你显然不想提取任何东西。你想要的只是删除一个单词,留下其余的单词。我会试试这样的。正则表达式适用于被空格包围的关键字或字符串开头或末尾的关键字。

    String[] s = {"Johnathan", "John Doe"};
     String keyWord = "John";
     for (String str : s) {
        str = str.replaceAll("(?:^|\\s+)"+keyWord+"(?:$|\\s+)", "");
        System.out.println(str);
     }
    

    印刷品

    Johnathan Doe
    Doe
    
        2
  •  0
  •   hitesh bedre    1 年前

    我们可以使用模式 "\\s?Doe\\s?" 因此,如果有任何起始或尾随空格字符,我们可以替换它(如果存在的话)。

    String regex = "\\s?Doe\\s?";
    String words[] = {"John Doe", "Johnathan Doe", "Doe John", "Doe"};
    for (String str : words) {
        String result = str.replaceAll(regex, "");
        System.out.println(str +" -> "+result);
     }
    

    输出:

    John Doe->约翰

    乔纳森·多伊->乔纳森

    Doe John->约翰

    Doe->

    代码链接: https://www.programiz.com/online-compiler/665f7P2R3oQRy