How to split string which has dollars($)

Suppose we have a string data1$$$data2$$$data3, how will you split it? If you use str.split(“$$$”) it will not split the string and instead return the same string only.

The split function takes a regular expression, not a string, to match. This regular expression uses a special character – in this case ‘$’ – so we would need to change it to escape that character:

So if we do this :

1
String[] split = str.split("\\$$$")

Even this does not work and does not split the string. Because we have 3 special characters($) and we need to escape each of them.

1
String[] split = str.split("\\$\\$\\$");

So this code finally splits the string properly. Same logic will apply to all special characters

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *