按分隔符数量拆分字符串 [英] Splitting a String by number of delimiters
本文介绍了按分隔符数量拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将一个字符串拆分为一个字符串数组,可能有多种组合,我试过了:
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+");
任何指导将不胜感激
推荐答案
用逗号分隔,用可选的空白字符括起来
To split with comma enclosed with optional whitespace chars you may use
s.split("\\s*,\\s*")
\s*,\s*
模式匹配
\s*
- 0+ 个空格,
- 逗号\s*
- 0+ 个空格
\s*
- 0+ whitespaces,
- a comma\s*
- 0+ whitespaces
如果您想确保没有前导/尾随空格,请考虑在拆分之前trim()
对字符串进行处理.
In case you want to make sure there are no leading/trailing spaces, consider trim()
ming the string before splitting.
这篇关于按分隔符数量拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文