【问题标题】:How to pick specific parts from a string? [closed]如何从字符串中选择特定部分? [关闭]
【发布时间】:2014-06-13 11:17:40
【问题描述】:
String s= "aaaaaaaaaaaBBBhelloDDDeeeeBBBworldDDDffffff";

我想将 BBB 和 DDD 之间的内容挑选成一个字符串数组String[] ss
这就是你好和世界这两个词。

有什么办法吗?

【问题讨论】:

  • 是的,有。正则表达式会以一种相当简单的方式做到这一点。但在此之前,我们可以看看你做了什么以及你面临的问题吗?
  • 你试过什么?这似乎是最直接的正则表达式使用

标签: java android


【解决方案1】:

您可以使用模式匹配:

 String s= "aaaaaaaaaaaBBBhelloDDDeeeeBBBworldDDDffffff";
        Pattern p = Pattern.compile("BBB(.+?)DDD",Pattern.DOTALL);
        Matcher m = p.matcher(s);
        ArrayList<String> sa = new ArrayList<String>();
        while (m.find()) {
          sa.add(m.group(1));
        }
        System.out.println(sa);

【讨论】:

    【解决方案2】:

    使用函数 substring(int beginIndex, int endIndex)。 如果您可以对索引进行硬编码。

    【讨论】:

      【解决方案3】:

      使用String.split("BBB")String.split("DDD")

      例如:

      String[] splitByBBB = s.split( "BBB" );
      /*
      in your String: 
      splitByBBB[0] is "aaaaaaaaaaa"
      splitByBBB[1] is "helloDDDeeee"
      splitByBBB[2] is "worldDDDffffff"
      */
      

      然后你使用split("DDD") 并获取第一个索引:

      String[] ss = new String[ splitByBBB.length - 1 ];
      for( int i = 0; i < splitByBBB.length; i++ )
      {
          ss[i] = splitByBBB[i + 1].split("DDD")[0];
      }
      /*
      in your String: 
      ss[0] is "hello"
      ss[1] is "world"
      */
      

      【讨论】:

        【解决方案4】:
        String[] array = s.split("BBB|DDD");
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-23
          • 1970-01-01
          • 1970-01-01
          • 2021-02-09
          • 2018-05-28
          相关资源
          最近更新 更多