Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.List;
- import java.util.ArrayList;
- import java.util.regex.Pattern;
- import java.util.regex.Matcher;
- public class Escape {
- public static void main(String[] args) {
- String[] ss = {
- "テスト1{=test1-string1/.test2-string2/}-終わり"
- , "-{-{-}-}-"
- , "-{-}-}-"
- , "-{-{-}-"
- , "-}{-"
- };
- for (String s: ss) {
- process(s);
- }
- }
- private static void process(String src) {
- System.out.format("src : %s\n", src);
- System.out.format("escape1: %s\n", escape1(src, '/', '-'));
- System.out.format("escape2: %s\n", escape2(src));
- System.out.println();
- }
- // http://stackoverflow.com/a/21791059
- private static List<Integer> stringToCodePoints(String in) {
- if( in == null)
- throw new NullPointerException("got null");
- List<Integer> out = new ArrayList<Integer>();
- final int length = in.length();
- for (int offset = 0; offset < length; ) {
- final int codepoint = in.codePointAt(offset);
- out.add(codepoint);
- offset += Character.charCount(codepoint);
- }
- return out;
- }
- private static String escape1(String src, char... cs) {
- char lbrace = '{';
- char rbrace = '}';
- StringBuilder sb = new StringBuilder();
- boolean in_brace = false;
- for (int c: stringToCodePoints(src)) {
- if (c == lbrace) {
- in_brace = true;
- sb.appendCodePoint(c);
- continue;
- }
- if (c == rbrace) {
- in_brace = false;
- sb.appendCodePoint(c);
- continue;
- }
- if (!in_brace) {
- sb.appendCodePoint(c);
- continue;
- }
- for (char e: cs) {
- if (c == e) {
- sb.appendCodePoint('\\');
- break;
- }
- }
- sb.appendCodePoint(c);
- }
- return sb.toString();
- }
- private static String escape2(String src) {
- Pattern balanced = Pattern.compile("(.*?\\{)(.*?\\})");
- Pattern special = Pattern.compile("[-/]");
- StringBuilder sb = new StringBuilder();
- int offset = 0;
- Matcher m = balanced.matcher(src);
- while (m.find()) {
- sb.append(m.group(1));
- sb.append(special.matcher(m.group(2)).replaceAll("\\\\$0"));
- offset = m.end();
- }
- sb.append(src.substring(offset));
- return sb.toString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement