1

How would you split this String format into parts:

message_type={any_text}&message_number={digits}&code={digits}&id={digits}&message={any_text}&timestamp={digits_with_decimal}

Where in the message={any_text} part, the {any_text} may contain a & and a = thus not being able to do String split by & or =

And the order of the message parts may be scrambled or not in this order. I am thinking that a pattern can be extracted for a solution, ={the_text_needed}& however this would not apply for the last part of the String as there will be no & at the end.

quarks
  • 33,478
  • 73
  • 290
  • 513

3 Answers3

1

I hope this will work -

String originalString = "message_type={a&=b}&message_number={1}&code={2}&id={3}&message={a&=b}&timestamp={12}";
Map<String, String> resultMap = new HashMap<String, String>();
String[] splitted1 = originalString.split("&+(?![^{]*})");
for (String str : splitted1) {
    String[] splitted2 = str.split("=+(?![^{]*})");
    resultMap.put(splitted2[0], splitted2[1]);
    splitted2 = null;
}

If parameter values are not enclosed within curly braces, then its really tough. I can think of a solution, but I don't know whether it could break in some situation or not -

String originalString = "message_type=msgTyp&message_number=1&code=2&message=a&=b&timestamp=12";
String[] predefinedParameters = {"message_type", "message_number", "code", "message", "timestamp"};
String delimeter = "###";

for (String str : predefinedParameters) {
    originalString = originalString.replace(str+"=", delimeter+str+"=");
}

originalString = originalString.substring(delimeter.length());

String[] result = originalString.split("&"+delimeter);
Kartic
  • 2,935
  • 5
  • 22
  • 43
0

Assuming that none of the fields contain & or =, you could:

String[] fields = message.split("&");
Map<String,String> fieldMap = new LinkedHashMap<>();
for (String field:fields)
{
    String[] fieldParts = field.split("=");
    fieldMap.put(fieldParts[0],fieldParts[1]);
}

and have a map of all your fields.

fdsa
  • 1,379
  • 1
  • 12
  • 27
0

That you are trying to do is to parse a querystring , you should check:

Query String Manipulation in Java

Community
  • 1
  • 1
Ricardo Umpierrez
  • 768
  • 2
  • 11
  • 24