I am working with strings and had a quick question. I have a string of text I extracted from a file and now want to create a string array with each sentence of the text, I understand I could use string.split(".");
for periods but how do I add question marks and exclamation marks. I tried string.split("." + "!" + "?");
but that didn't seem to work. Any help would be appreciated!
string.split(".")
does not work as you expect it does...
String s = "Hello.world";
System.out.println(Arrays.toString(s.split("."))); // outputs []
Split method takes a regex .
String s = "Hello.world";
System.out.println(Arrays.toString(s.split("\\."))); // outputs [Hello, world]
The regex of ".!?"
says "any character followed by zero or more !
" (which effectively is the same result as just "."
)
If you want to split on individual characters, use a character class
string.split("[.!?]")
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.