简体   繁体   English

Java:基于2个分隔符的regex split()

[英]Java : regex split() based on 2 delimiters

I want to split a string when space is followed by comma. 我希望在空格后面跟逗号分割字符串。

My input String : 我的输入字符串:

go back, to work !  ,2012-10-01 07:01:45,,  1

Output Expected: 产量预期:

"go back, to work !"    
"2012-10-01 07:01:45,,1"

Code I tried: 我试过的代码:

String[] b1=a1.split("[\\s,]");

But this splits the string only based on whitespaces. 但是这只根据空格分割字符串。 I want to split it when there is both whitespace and comma not just either one. 当有空格和逗号时,我想分开它而不是其中之一。 What should I do? 我该怎么办?

Split on space followed by comma : 空格上分隔后跟逗号

String[] b1 = a1.split("\\s,");

[\\\\s,] is a character class and it will split on space or comma. [\\\\s,]是一个字符类,它将在空格或逗号上分割。

使用此选项可在出现空格时分割字符串,然后出现逗号。

String[] b1 = a1.split(" ,");

Split on space followed by comma using ("\\\\s,") will not give you the desired output of 拆分空格后跟逗号("\\\\s,")将不会给你想要的输出

"go back, to work !"

"2012-10-01 07:01:45"

1

The output will be 输出将是

go back, to work !

2012-10-01 07:01:45,, 1

Either you can use comma followed by space or space followed by comma using "\\\\s,|,\\\\s" then you will get below output 您可以使用逗号后跟空格或空格,然后使用逗号"\\\\s,|,\\\\s"那么您将得到以下输出

go back

to work !

2012-10-01 07:01:45,

1

However it's still not same as what you wanted. 然而,它仍然与你想要的不一样。 You might want to clarify your requirement. 您可能想澄清您的要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM