Skip to content
Advertisement

How to split a String with two delimiters and keep only one of of them?

I want to split a String in punctuation marks and white spaces, but keep the punctuation marks. E.x

JavaScript

I want to have as a result

JavaScript

but instead I get

JavaScript

what I used was example.toLowerCase().trim().split("(?<=\b|[^\p{L}])");

Advertisement

Answer

Why are you doing toLowerCase()? This already messes up your expected result. And why the trim() on the full string?

Doing this with a single split call is probably not too simple.

An alternative would be to just filter out the unwanted entries:

JavaScript

Output:

JavaScript

Reacting to your comment of wanting [How,are,you,?,I,am,fine,!] as output; simply dont print with Arrays.toString but build the string yourself manually. The array does not contain any whitespaces.

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement