2

I need to split my string with any occurrence of $$ for this string:

String tmpHash = "NA$notValid-1$notValid-2##notValid-3##$$VALID-1##$$VALID-2##$notvalid-4$$VALID-3";

Here is my code:

String[] arr=tmpHash.split("$$");

        for (int i = 0; i < arr.length; i++) {
            System.out.println("OUTPUT--> "+arr[i]);    

        }

OUTPUT IS

OUTPUT--> NA$notValid-1$notValid-2##notValid-3##$$VALID-1##$$VALID-2##$notvalid-4$$VALID-3

DESIRED OUTPUT

OUTPUT-->NA$notValid-1$notValid-2##notValid-3##
OUTPUT-->VALID-1##
OUTPUT-->VALID-2##$notvalid-4
OUTPUT-->VALID-3
Josh Lowe
  • 486
  • 3
  • 13
ravz
  • 968
  • 10
  • 21

2 Answers2

5

You would have to escape the $ sign.

String[] arr=tmpHash.split("\\$\\$");

Or use (according to this answer to a similar question)

String myString = "$$";
String escapedString = java.util.regex.Pattern.quote(myString)

to automatically escape all special regex characters in a given string.

Community
  • 1
  • 1
AntonH
  • 6,359
  • 2
  • 30
  • 40
  • 2
    @ravz So it seems strange you didn't accept this answer then... – Duncan Jones Jun 18 '14 at 13:37
  • @AntonH Although your final paragraph looks rather similar to the end of [this answer](http://stackoverflow.com/a/3853764/474189). If you "borrowed" it, you should probably give credit where it's due. – Duncan Jones Jun 18 '14 at 13:40
  • @Duncan I didn't know how to reference an answer, and then got distracted . My apologies. Edited to reference answer. – AntonH Jun 18 '14 at 13:54
1

Best and short answer for splitting string having $$ is here we will be escaping $ because it is used in regex internally.

String[] arr=tmpHash.split("\\$\\$");
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
visha
  • 58
  • 7