【问题标题】:Remove a substring from a string starting from a character从一个字符开始的字符串中删除一个子字符串
【发布时间】:2016-06-24 19:24:03
【问题描述】:

旁白:孩子们,如果你是单身的话,以后会很幸福。 [标题:2030年]。但只有你的一个故事可以结束 大大地。其余的以有人受伤而告终。这是其中之一 故事,它开始......从一件衬衫开始。

从上面的字符串中,我将如何删除被 [] 包围的句子。于是,这个

[标题:2030年]。

将被取出。然后字符串变为

旁白:孩子们,当你单身时,你所寻找的只是从此过上幸福的生活。但只有你的一个故事可以这样结束。其余的以有人受伤而告终。这是其中一个故事,它从一件衬衫开始。

【问题讨论】:

  • 那么你想提取那部分还是从主字符串中删除它?
  • 从主字符串中删除它
  • replaceAll 解决方案很棒,或者干脆使用好的 ol' indexof / substring 方法
  • 顺便说一句,它来自 HIMYM 吗? :P

标签: java string substring


【解决方案1】:

您可以使用带有String.replaceAll(String, String) 的正则表达式,但您需要转义[] 字符(因为它们在正则表达式中具有特殊含义)。类似的,

String story = "Narrator: Kids, if you are single is all this happy "
    + "ever after. [Title: the year of 2030]. But only one of your stories "
    + "can end that way. The rest end with someone getting hurt. "
    + "This is one of those stories, and it starts… with a shirt.";
story = story.replaceAll("\\[.*\\]", "");
System.out.println(story);

【讨论】:

  • \\[.*\\] 如果有 2 个,它也会删除它们之间的所有内容:P
【解决方案2】:

试试这个:

public static void main(String[] args) {
    String s = "Narrator: Kids, if you are single is all this happy ever after. [Title: the year of 2030]. But only one of your stories can end that way. The rest end with someone getting hurt. This is one of those stories, and it starts… with a shirt.";
    System.out.println(s.replaceAll("\\[.*?\\]", ""));
}

O/P:

旁白:孩子们,如果你是单身的话,以后会很幸福。 .但 只有你的一个故事可以这样结束。其余的以某人结束 受到伤害。这是其中一个故事,它开始...... 衬衫。

【讨论】:

    【解决方案3】:

    或者你可以试试这个。

    String str = "Narrator: Kids,if you are single is all this happy ever after. [Title: the year of 2030]. But (...)";
        StringBuilder strBuild = new StringBuilder(str);
    
          int start = str.indexOf("[");
          int end = str.indexOf("]")+1;
        strBuild.delete(start, end);
        System.out.println(strBuild);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 2023-01-28
      • 1970-01-01
      • 1970-01-01
      • 2013-03-02
      • 1970-01-01
      相关资源
      最近更新 更多