Advertisement
cd62131

Escape special chars

Apr 19th, 2017
284
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 2.29 KB | None | 0 0
  1. import java.util.List;
  2. import java.util.ArrayList;
  3. import java.util.regex.Pattern;
  4. import java.util.regex.Matcher;
  5. public class Escape {
  6.   public static void main(String[] args) {
  7.     String[] ss = {
  8.       "テスト1{=test1-string1/.test2-string2/}-終わり"
  9.       , "-{-{-}-}-"
  10.       , "-{-}-}-"
  11.       , "-{-{-}-"
  12.       , "-}{-"
  13.     };
  14.     for (String s: ss) {
  15.       process(s);
  16.     }
  17.   }
  18.  
  19.   private static void process(String src) {
  20.     System.out.format("src    : %s\n", src);
  21.     System.out.format("escape1: %s\n", escape1(src, '/', '-'));
  22.     System.out.format("escape2: %s\n", escape2(src));
  23.     System.out.println();
  24.   }
  25.  
  26.   // http://stackoverflow.com/a/21791059
  27.   private static List<Integer> stringToCodePoints(String in) {
  28.     if( in == null)
  29.       throw new NullPointerException("got null");
  30.     List<Integer> out = new ArrayList<Integer>();
  31.     final int length = in.length();
  32.     for (int offset = 0; offset < length; ) {
  33.       final int codepoint = in.codePointAt(offset);
  34.       out.add(codepoint);
  35.       offset += Character.charCount(codepoint);
  36.     }
  37.     return out;
  38.   }
  39.  
  40.   private static String escape1(String src, char... cs) {
  41.     char lbrace = '{';
  42.     char rbrace = '}';
  43.     StringBuilder sb = new StringBuilder();
  44.     boolean in_brace = false;
  45.     for (int c: stringToCodePoints(src)) {
  46.       if (c == lbrace) {
  47.         in_brace = true;
  48.         sb.appendCodePoint(c);
  49.         continue;
  50.       }
  51.       if (c == rbrace) {
  52.         in_brace = false;
  53.         sb.appendCodePoint(c);
  54.         continue;
  55.       }
  56.       if (!in_brace) {
  57.         sb.appendCodePoint(c);
  58.         continue;
  59.       }
  60.       for (char e: cs) {
  61.         if (c == e) {
  62.           sb.appendCodePoint('\\');
  63.           break;
  64.         }
  65.       }
  66.       sb.appendCodePoint(c);
  67.     }
  68.     return sb.toString();
  69.   }
  70.  
  71.   private static String escape2(String src) {
  72.     Pattern balanced = Pattern.compile("(.*?\\{)(.*?\\})");
  73.     Pattern special = Pattern.compile("[-/]");
  74.     StringBuilder sb = new StringBuilder();
  75.     int offset = 0;
  76.     Matcher m = balanced.matcher(src);
  77.     while (m.find()) {
  78.       sb.append(m.group(1));
  79.       sb.append(special.matcher(m.group(2)).replaceAll("\\\\$0"));
  80.       offset = m.end();
  81.     }
  82.     sb.append(src.substring(offset));
  83.     return sb.toString();
  84.   }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement