【问题标题】:Creating new strings from one string从一个字符串创建新字符串
【发布时间】:2020-12-17 11:13:40
【问题描述】:

我有以下字符串:

+420354599951 [table] +420354599969 [table] +420354599969 [fax] +420354599969 [mobile]

每次出现 [table]、[fax] 或 [mobile] 时,我都需要将其分开。 所以我需要从这个字符串创建 4 个不同的字符串:

+420354599951 [table]
+420354599969 [table]
+420354599969 [fax]
+420354599969 [mobile]

【问题讨论】:

    标签: java string split


    【解决方案1】:

    使用正则表达式拆分字符串,(?=\\+) 其中?= 指定positive lookahead assertion

    演示:

    class Main {
        public static void main(String[] args) {
            String str = "+420354599951 [table] +420354599969 [table] +420354599969 [fax] +420354599969 [mobile]";
            String[] parts = str.split("(?=\\+)");
    
            // Display each element from the array
            for (String part : parts) {
                System.out.println(part);
            }
        }
    }
    

    输出:

    +420354599951 [table] 
    +420354599969 [table] 
    +420354599969 [fax] 
    +420354599969 [mobile]
    

    【讨论】:

    • Arrays.stream(str.split("\\]\\s*")).map(x -> String.format("%s]", x)).forEach(System.out::println);
    • @ElliottFrisch - 是的,这可以是另一种方式。
    • 嗯,它实际上与此相同(稍微简单的正则表达式,具有不同的权衡)。这就是我将其作为评论留下的原因。
    • @ElliottFrisch - 感谢您的加入。当像你这样的天才回答或解决问题时,它会帮助很多人!
    【解决方案2】:

    让@ElliottFrisch 的示例更进一步,您可以使用Java Stream API Collectors 将字符串保存在List 中,如下所示:

    List<String> numbers = Arrays.stream(str.split("\\]\\s*"))
        .map(x -> String.format("%s]", x))
        .collect(Collectors.toList());
    

    【讨论】:

      【解决方案3】:

      您可以为此目的使用正则表达式:

      String str = "+420354599951 [table] +420354599969 [table] " +
              "+420354599969 [fax] +420354599969 [mobile]";
      
      String[] arr = Arrays.stream(str
              // replace sequences (0 and more)
              // of whitespace characters
              // after closing square brackets
              // with delimiter characters
              .replaceAll("(])(\\s*)", "$1::::")
              // split this string by
              // delimiter characters
              .split("::::", 0))
              .toArray(String[]::new);
      
      // output in a column
      Arrays.stream(arr).forEach(System.out::println);
      

      输出:

      +420354599951 [table]
      +420354599969 [table]
      +420354599969 [fax]
      +420354599969 [mobile]
      

      另见:How to split a string delimited on if substring can be casted as an int

      【讨论】:

        猜你喜欢
        • 2012-11-27
        • 1970-01-01
        • 2013-08-11
        • 1970-01-01
        • 1970-01-01
        • 2016-01-11
        • 2012-03-12
        • 2019-02-16
        • 1970-01-01
        相关资源
        最近更新 更多