I have been using myString.split("\\s+");
to get the each word. But now I want to split the commas and full stops aswell. For Example:
Mama always said life was like a box of chocolates, you never know what you're gonna get.
to:
{Mama, always, said, life, was, like, a, box, of, chocolates ,,, You, never, know, what, you're, gonna, get,.,}
How would one go about doing this?
To split a string with comma, use the split() method in Java. str. split("[,]", 0);
To split a string by space or comma, pass the following regular expression to the split() method - /[, ]+/ . The method will split the string on each occurrence of a space or comma and return an array containing the substrings.
In order to parse a comma-delimited String, you can just provide a "," as a delimiter and it will return an array of String containing individual values. The split() function internally uses Java's regular expression API (java. util. regex) to do its job.
Example 4: Split String by Multiple Delimiters Java program to split a string with multiple delimiters. Use regex OR operator '|' symbol between multiple delimiters. In the given example, I am splitting the string with two delimiters hyphen and dot.
If commas and periods are always followed by whitespace or end-of-string, then you can write:
myString.split("(?=[,.])|\\s+");
If they're not and you want e.g. a,b
to be split into three strings, then:
myString.split("(?<=[,.])|(?=[,.])|\\s+");
You could use a lookahead to split before dots and commas, too:
myString.split("\\s+|(?=[,.])");
That the lookahead is not included in the actual match, so the actual character (comma or period) will end up in the resultant array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With