问题
I would like to split a string using multiple delimiters. Right now I am using this:
String delims = "[\\s;.,:'!?()]";
which seems to work fine for those characters, but when I try to add the -
character, it yells at me. How can I use all of these characters plus -
as delimiters to split my string? Thanks in advance!
回答1:
-
has a special meaning in character classes, indicating ranges. (E.g. [0-9]
will match any digit.)
However, if you put if you put it either as the first character or the last it will be matched as a literal -
.
回答2:
- inside the character class has a special meaning. It is usually used to select a range of characters like: [a-z] ... In order to match the dash alone ... either keep it in the beginning or the end
I just tried this and it worked
String regex = "[\\s;.,:'!?()-]";
String text = "jatin-shah-testing";
String[] tokens = text.split(regex);
for(int i = 0; i < tokens.length; i++)
System.out.println(tokens[i]);
来源:https://stackoverflow.com/questions/15774500/splitting-string-using-multiple-delimiters-java