问题
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