1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.parsing;
17
18
19
20
21 public class GenericTokenParser {
22
23 private final String openToken;
24 private final String closeToken;
25 private final TokenHandler handler;
26
27 public GenericTokenParser(String openToken, String closeToken, TokenHandler handler) {
28 this.openToken = openToken;
29 this.closeToken = closeToken;
30 this.handler = handler;
31 }
32
33 public String parse(String text) {
34 if (text == null || text.isEmpty()) {
35 return "";
36 }
37
38 int start = text.indexOf(openToken);
39 if (start == -1) {
40 return text;
41 }
42 char[] src = text.toCharArray();
43 int offset = 0;
44 final StringBuilder builder = new StringBuilder();
45 StringBuilder expression = null;
46 do {
47 if (start > 0 && src[start - 1] == '\\') {
48
49 builder.append(src, offset, start - offset - 1).append(openToken);
50 offset = start + openToken.length();
51 } else {
52
53 if (expression == null) {
54 expression = new StringBuilder();
55 } else {
56 expression.setLength(0);
57 }
58 builder.append(src, offset, start - offset);
59 offset = start + openToken.length();
60 int end = text.indexOf(closeToken, offset);
61 while (end > -1) {
62 if (end > offset && src[end - 1] == '\\') {
63
64 expression.append(src, offset, end - offset - 1).append(closeToken);
65 offset = end + closeToken.length();
66 end = text.indexOf(closeToken, offset);
67 } else {
68 expression.append(src, offset, end - offset);
69 break;
70 }
71 }
72 if (end == -1) {
73
74 builder.append(src, start, src.length - start);
75 offset = src.length;
76 } else {
77 builder.append(handler.handleToken(expression.toString()));
78 offset = end + closeToken.length();
79 }
80 }
81 start = text.indexOf(openToken, offset);
82 } while (start > -1);
83 if (offset < src.length) {
84 builder.append(src, offset, src.length - offset);
85 }
86 return builder.toString();
87 }
88 }