1

I am spliting string with '&' . For Example:

password=XXXXXXXXX&username=XXXXXXXXXXX

Now if suppose my password contains '&' then i am facing issue here that the password gets trimed on first occurence of '&'.

Example:

password=disney&123&username=XXXXXXXXXXX

So my output will be as follows:

password=disney 
123 
username=XXXXXXXXXXX

But I want my output as:

password=disney&123 
username=XXXXXXXXXXX

Please guide me as i am new to java. And i want to split the string using '&' only and my password may conatin '&' it depends on users.

Thanks in Advance, Ritesh

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

2 Answers2

2

A more simple solution would be to use the URL encoding completly. Here you are using only the separator system but you should also use the encoding.

So when you build the String, encode the values, this will replace some character, you can use the complet solution or simply replace the & with the value of your choice (but I would not do that).

Then, when you have split the String contains only the & used to separate values, decode the values (to recreate the original values).

This would be exactly the same as sending a request to a WebService, since you use the same pattern, this would seems more logic.

  • Encode the values
  • Concat the values with &
  • Send the String
  • Split the String using &
  • Decode the values
Community
  • 1
  • 1
AxelH
  • 14,325
  • 2
  • 25
  • 55
1
String[] strs="password=disney&123&username=XXXXXXXXXXX".split("&username=");
strs[1]="username="+strs[1];
System.out.println(strs[0]);
System.out.println(strs[1]);

--

Edit:

//This is a slightly more generalized method
String[] strs="username=XXXXXXXXXXX&password=disney&123".split("&(?=(username|password)=)");
System.out.println(strs[0]);
System.out.println(strs[1]);

--

Edit:

//more generalized method
String[] strs="username=XXXXXXXXXXX&password=disney&123".split("&(?=([a-zA-Z0-9]+)=)");
for(String str : strs)
    System.out.println(str);
cshu
  • 5,654
  • 28
  • 44
  • But then what if the string it receives is formatted as "username=XXX$password=YYY"? From what OP is suggesting, it sounds like it should also be a parseable value. – MikaelF Feb 13 '17 at 06:56
  • @MikaelF OP's example is not url encoded (`password` contains unescaped literal `&`). For custom format, we need custom parser. Anyway I'll add a slightly more generalized method. – cshu Feb 13 '17 at 07:18
  • Thanks for your help. But this username and password is part of querystring in a url. The length i.e.. the number of parameters used to query may change for example it can be: – Ritesh Khatri Feb 13 '17 at 07:33
  • saml=xxxxxxxxx&password=xxxxxxxxx&appVersion=xxxxxxxxxxxxxxx&username=xxxxxxxxxxxxx&token=xxxxxxxx – Ritesh Khatri Feb 13 '17 at 07:33
  • So i need a more generalized solution – Ritesh Khatri Feb 13 '17 at 07:34
  • @RiteshKhatri added. – cshu Feb 13 '17 at 07:38