Skip to content
Advertisement

Splitting a string using special characters and keeping them

I’m trying to split a string with special characters and not being able to split the parentheses properly. This the code I’m trying :

JavaScript

The regex does not split the starting parentheses (

I’m trying to get the following output:

JavaScript

Could someone please help me. Thank you.

output of the code

Advertisement

Answer

So you want to use split() to get every character separately, except for spaces and commas, so split by spaces/commas and by “nothing”, i.e. the zero-width “space” between non-space/comma characters.

JavaScript

Output

JavaScript

Alternative: Search for what you want, and collect it into an array or List (requires Java 9):

JavaScript

Same output.

For older versions of Java, use a find() loop:

JavaScript

Output

JavaScript

You can always convert the List to an array:

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