0

I have a response that I am getting from a server. The response needs to be split using the delimiter "=" but for one of the argument there is "=" in its value which needs to be included as well. Example: Response: Name=Hi&Code=Ind=&Age=23

Once I get this response I split the string with & as delimiter. Next I split it with delimiter = but in this case code should have the value as Ind= but it is coming as Ind . I have other functions as well where I am using the same split function for parsing the response. Is there any regex or delimiter I can use which will be the best for my usecase here.

I tried different approach of include ahead delimiter regex but they didn't work.

Rohit Dubey
  • 41
  • 1
  • 9

1 Answers1

0

I think what you want to do here is to use String#split along with its second limit parameter, which controls how many times the split is applied. In this case, we want to split on = just once.

String input = "Name=Hi&Code=Ind=&Age=23";
String[] parts = input.split("&");
for (String part : parts) {
    String key = part.split("=", 2)[0];
    String value = part.split("=", 2)[1];
    System.out.println("Found a (key, value): (" + key + ", " + value + ")");
}

This prints:

Found a (key, value): (Name, Hi)
Found a (key, value): (Code, Ind=)
Found a (key, value): (Age, 23)
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360