【问题标题】:Split comma-separated string but ignore comma followed by a space拆分逗号分隔的字符串,但忽略逗号后跟空格
【发布时间】:2018-02-25 23:16:34
【问题描述】:

public static void main(String[] args) {

String title = "Today, and tomorrow,2,1,2,5,0";
String[] titleSep = title.split(",");
System.out.println(Arrays.toString(titleSep));
System.out.println(titleSep[0]);
System.out.println(titleSep[1]);

}

输出: [今天,明天,2,1,2,5,0]

今天

(空间)和明天

我想将“今天和明天”视为表示 titleSep 的第一个索引值的短语(不想在它包含的逗号处分隔)。 什么是 split 方法参数,它只在逗号而不是空格处拆分字符串? (Java 8)

【问题讨论】:

    标签: java


    【解决方案1】:

    使用负面的展望:

    String[] titleSep = title.split(",(?! )");
    

    正则表达式(?! ) 表示“当前位置后面的输入不是空格”。

    仅供参考,负面展望采用(?!<some regex>) 形式,正面展望采用(?=<some regex>) 形式

    【讨论】:

      【解决方案2】:

      split 函数的参数是一个正则表达式,因此我们可以使用负前瞻来按逗号不跟随空格进行分割:

      String title = "Today, and tomorrow,2,1,2,5,0";
      String[] titleSep = title.split(",(?! )");  // comma not followed by space
      System.out.println(Arrays.toString(titleSep));
      System.out.println(titleSep[0]);
      System.out.println(titleSep[1]);
      

      输出是:

      [Today, and tomorrow, 2, 1, 2, 5, 0]
      Today, and tomorrow
      2 
      

      【讨论】:

        猜你喜欢
        • 2010-12-17
        • 1970-01-01
        • 2021-07-09
        • 1970-01-01
        • 2015-03-07
        • 1970-01-01
        • 2011-12-25
        相关资源
        最近更新 更多