Convert strings with both quotes and ticks into a valid xpath component For example, foo will be converted to "foo", f"oo will be converted to 'f"oo', foo'"bar will be converted to concat("foo'", '"', "bar") @param toEscape a text to e
(String toEscape)
| 34 | * @return the same text with escaped quoted, e.g. {@code "\"f'oo\""} |
| 35 | */ |
| 36 | @SuppressWarnings("JavaDoc") |
| 37 | public static String escape(String toEscape) { |
| 38 | if (toEscape.contains("\"") && toEscape.contains("'")) { |
| 39 | boolean quoteIsLast = toEscape.lastIndexOf("\"") == toEscape.length() - 1; |
| 40 | String[] substringsWithoutQuotes = toEscape.split("\""); |
| 41 | |
| 42 | StringBuilder quoted = new StringBuilder("concat("); |
| 43 | for (int i = 0; i < substringsWithoutQuotes.length; i++) { |
| 44 | quoted.append("\"").append(substringsWithoutQuotes[i]).append("\""); |
| 45 | quoted.append( |
| 46 | ((i == substringsWithoutQuotes.length - 1) |
| 47 | ? (quoteIsLast ? ", '\"')" : ")") |
| 48 | : ", '\"', ")); |
| 49 | } |
| 50 | return quoted.toString(); |
| 51 | } |
| 52 | |
| 53 | // Escape string with just a quote into being single quoted: f"oo -> 'f"oo' |
| 54 | if (toEscape.contains("\"")) { |
| 55 | return String.format("'%s'", toEscape); |
| 56 | } |
| 57 | |
| 58 | // Otherwise return the quoted string |
| 59 | return String.format("\"%s\"", toEscape); |
| 60 | } |
| 61 | } |