Splitting a String by number of delimiters

旧城冷巷雨未停 提交于 2021-02-17 02:40:29

问题


I am trying to split a string into a string array, there might be number of combinations, I tried:

String strExample = "A, B";
//possible option are:

1. A,B 
2. A, B
3. A , B
4. A ,B

String[] parts;
parts = strExample.split("/"); //Split the string but doesnt remove the space in between them so the 2 item in the string array is space and B ( B)
parts = strExample.split("/| ");
parts = strExample.split(",|\\s+");

Any guidance would be appreciated


回答1:


To split with comma enclosed with optional whitespace chars you may use

s.split("\\s*,\\s*")

The \s*,\s* pattern matches

  • \s* - 0+ whitespaces
  • , - a comma
  • \s* - 0+ whitespaces

In case you want to make sure there are no leading/trailing spaces, consider trim()ming the string before splitting.




回答2:


You can use

parts=strExample.split("\\s,\\s*");

for your case.



来源:https://stackoverflow.com/questions/53831649/splitting-a-string-by-number-of-delimiters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!