For a long time I have been tormenting the problem. There are lines of approximately the following format: registrationNumber: "" 074-p "" registrationNumber: "074" -p "registrationNumber:" "07" 4-p "" After a colon, there are always external quotes, the number of nested quotes can be arbitrary. I can not in any way implement a way to escape quotes nested in basic ones. Help me please.

  • But why do you want to screen them and how do you want to screen them with a backslash \? - Farkhod Daniyarov
  • backslash, the fact is that only, as it turned out only in this format (registrationNumber: "\" 074-p \ ""), the server receives the data. The reasons can not say, I found out empirically. - M Dmitry
  • Replace the symbol number, not? - Alrott SlimRG

1 answer 1

It seems possible so.

public class HelloWorld { public static void main(String[] args) { String s = "egistrationNumber:\"074\"-р\""; System.out.println(s); String replacedStr = s.replaceAll("\"", "\\\\\""); System.out.println(replacedStr); } } 

ouput:

 egistrationNumber:"074"-р" egistrationNumber:\"074\"-р\" 

UDP:

 public class HelloWorld { public static void main(String[] args) { String[] arrays = { "registrationNumber:\"\"074-р\"\"", "registrationNumber:\"074\"-р\"", "registrationNumber:\"\"07\"4-р\"\"", }; Pattern pattern = Pattern.compile("(.+:)\"(.+)\""); for (String string : arrays) { Matcher matcher = pattern.matcher(string); if (matcher.find()) { String result = matcher.group(2).replace("\"", "\\\""); String newString = matcher.group(1) + "\"" + result + "\""; System.out.println("NewString: " + newString); } else { System.out.println("Не найден: " + string); } } } } 

ouput:

 NewString: registrationNumber:"\"074-р\"" NewString: registrationNumber:"074\"-р" NewString: registrationNumber:"\"07\"4-р\"" 

See the Java online demo .

  • Thanks, but in this case all quotes are escaped, and some entity that checks the string need external quotes to remain unshielded. Like this: egistrationNumber: "074 \" - p ", or like this: registrationNumber:" \ "074-p \" " - M Dmitry
  • Regular to replace all quotes with quotes with a backslash is not needed. .replaceAll("\"", "\\\\\"") = .replace("\"", "\\\"") . - Wiktor Stribiżew
  • @WiktorStribiżew try to start, you’ll just get egregistrationNumber: \ 074 \ -р` - Farkhod Daniyarov
  • @Mdmitry good, now I will try, maybe it will work :) - Farkhod Daniyarov
  • @Dmitry updated the code, maybe what you need, although it is possible the solution is not the best - Farkhod Daniyarov 1:38 pm