String text = "Good morning. Have a good class. " +
"Have a good visit. Have fun!";
String[] words = text.split("[ \n\t\r.,;:!?(){");
This split
method is provided in text book, meant to remove all the delimiters in the sentence as well as white space character but clearly it is not working and throws a regex exception to my disappointment....I am wondering what could we do here to make it work? The requirement is after the split
method, everything in the `String[] words are either just English words without any delimiters attaching to it or whitespace character! Thanks a lot!
You are missing closing ]
in your character class:
String[] words = text.split("[ \n\t\r.,;:!?(){]");
btw you can just do (and it is better option):
String[] words = text.split("\\W+");
to split on any non-word character.
String.split()
is NOT for removing characters. It is used to divide the String
into smaller substrings.
Example:
String s = "This is a string!";
String[] tokens = s.split(" ");
Split will have used the String " " (one space character) as a delimiter to, well, split the string. As a result, the array tokens
will look something like
{"This", "is", "a", "string!"}
If you want to remove characters, try taking a look at String.replaceAll()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.