Natalie Rose
Natalie Rose

Reputation: 237

Java Regex not working?

I am trying to send the following parameters to a server through HTTP POST:

["my_session_id","{this=that, foo=bar}"]

But the server is returning a parse error because of the quotes around the hash.

I am trying to remove them with a regex like so:

params.replaceAll("\\\"\\{", "\\{");
params.replaceAll("\\\"\\}", "\\}");

In all honestly I have no idea what I'm doing. Please help.

Thanks in advance!

Upvotes: 0

Views: 112

Answers (2)

notoriousb1t
notoriousb1t

Reputation: 1

Is there a reason you are using the regular expression replaceAll? Alternatively, you might try:

 String parameters = parameters.replace("{", "\\{").replace("}", "\\}");

Upvotes: 0

Cat
Cat

Reputation: 67502

There's two issues here: First, you're not re-assigning the string. Strings are immutable in Java (cannot be changed), so you must assign the result. Second, you're replacing "} instead of }".

Here's what I used:

String params = "[\"my_session_id\",\"{this=that, foo=bar}\"]";
params = params.replaceAll("\\\"\\{", "\\{");
params = params.replaceAll("\\}\\\"", "\\}");
System.out.println(params);

Which prints out:

["my_session_id",{this=that, foo=bar}]

PS: Bit of advice, use JSON. Android has excellent JSON handling, and it is supported in PHP as well.

Upvotes: 2

Related Questions