Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java string – regex replace for pattern

I’ve a json string. I would like to replace all instances of:

...
...
"style":[["1","2"]]
...
"style":["1"]
...
"style":[["1","3","5","8"]]

to:

...
...
"style":["1","2"]
...
"style":["1"]
...
"style":["1","3","5","8"]

How can I do it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For best results, you should probably use a JSON parser. If all style keys would always be either singly or doubly nested arrays of strings, then a regex replace all might be sufficient:

String input = "\"style\":[[\"1\",\"3\",\"5\",\"8\"]]";
String output = input.replaceAll("\"style\":\\s*\\[\\[(.*?)\\]\\]", "\"style\":[$1]");
System.out.println(output);  // "style":["1","3","5","8"]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading