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!
Asked
Active
Viewed 228 times
0
Java Devil
- 10,629
- 7
- 33
- 48
Ahmed Kidwai
- 1
- 4
-
`string.split("[.!?]")` – Jun 09 '17 at 01:44
1 Answers
3
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("[.!?]")
OneCricketeer
- 179,855
- 19
- 132
- 245
-
2And since its a sentence if you want to retain the split character `(?<=[.!?])` – Java Devil Jun 09 '17 at 01:49