分割逗号分隔的字符串,但忽略逗号后跟空格 [英] Split comma-separated string but ignore comma followed by a space

查看:84
本文介绍了分割逗号分隔的字符串,但忽略逗号后跟空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static void main(String [] args){

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]

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

今天

(空格)和明天

我想将今天和明天"视为代表titleSep的第一个索引值的短语(不想以逗号分隔).什么是split方法参数,它将仅以逗号分隔字符串而不用空格分隔?(Java 8)

I want to treat "Today, and tomorrow" as a phrase representing the first index value of titleSep (do not want to separate at comma it contains). What is the split method argument that would split the string only at commas NOT followed by a space? (Java 8)

推荐答案

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

The argument to the split function is a regex, so we can use a negative lookahead to split by comma-not-followed-by-space:

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 

这篇关于分割逗号分隔的字符串,但忽略逗号后跟空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆