Ahmed Kidwai
Ahmed Kidwai

Reputation: 1

Splitting a string in java with more than one split parameter

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!

Upvotes: 0

Views: 282

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191874

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("[.!?]")

Upvotes: 3

Related Questions