独角兽企业重金招聘Python工程师标准>>>
private Pattern ptn = pile(".*?'");public String escapeSingleQuota(String origin) {Matcher m = ptn.matcher(origin);StringBuffer sb = new StringBuffer();int end = 0;while(m.find()) {end = m.end();String seg = origin.substring(m.start(), end);int len = seg.length();if (len == 1) {if ('\'' == seg.charAt(0)) {sb.append("\\'");} else {sb.append(seg);}} else { // len > 1sb.append(seg.substring(0, seg.length() - 2));char lastcSec = seg.charAt(seg.length() - 2);if (lastcSec == '\\') {sb.append("\\'");} else {sb.append(lastcSec);sb.append("\\'");}}}if (end < origin.length()) {sb.append(origin.substring(end));}return sb.toString();}
@Testpublic void tresource() throws IOException {String c = new String(ByteStreams.toByteArray(applicationContext.getResource("classpath:fixtures/string/singlequota.txt").getInputStream()));c = hct.escapeSingleQuota(c);assertThat(c, equalTo("\\'abcu\\'\\'\\'zz"));}@Testpublic void t() {String s = "'''''a\\'";String news = hct.escapeSingleQuota(s);assertThat(news, equalTo("\\'\\'\\'\\'\\'a\\'"));s = "\'''''a\\'";news = hct.escapeSingleQuota(s);assertThat(news, equalTo("\\'\\'\\'\\'\\'a\\'"));s = "\'\'\'\''a\\'";news = hct.escapeSingleQuota(s);assertThat(news, equalTo("\\'\\'\\'\\'\\'a\\'"));}