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 StringBuilder builder = new StringBuilder();
35 if (text != null && text.length() > 0) {
36 char[] src = text.toCharArray();
37 int offset = 0;
38 int start = text.indexOf(openToken, offset);
39 while (start > -1) {
40 if (start > 0 && src[start - 1] == '\\') {
41
42 builder.append(src, offset, start - offset - 1).append(openToken);
43 offset = start + openToken.length();
44 } else {
45 int end = text.indexOf(closeToken, start);
46 if (end == -1) {
47 builder.append(src, offset, src.length - offset);
48 offset = src.length;
49 } else {
50 builder.append(src, offset, start - offset);
51 offset = start + openToken.length();
52 String content = new String(src, offset, end - offset);
53 builder.append(handler.handleToken(content));
54 offset = end + closeToken.length();
55 }
56 }
57 start = text.indexOf(openToken, offset);
58 }
59 if (offset < src.length) {
60 builder.append(src, offset, src.length - offset);
61 }
62 }
63 return builder.toString();
64 }
65
66 }