6
7 // Process substitution string to replace group references with groups
8 int cursor = 0;
9 StringBuilder result = new StringBuilder();
10
11 while (cursor < replacement.length()) {
12 char nextChar = replacement.charAt(cursor);
13 if (nextChar == '\\') {
14 cursor++;
15 if (cursor == replacement.length())
16 throw new IllegalArgumentException("character to be escaped is missing");
17 nextChar = replacement.charAt(cursor);
18 result.append(nextChar);
19 cursor++;
20 } else if (nextChar == '$') {
21 // Skip past $
22 cursor++;
23 // Throw IAE if this "$" is the last character in replacement
24 if (cursor == replacement.length())
25 throw new IllegalArgumentException("Illegal group reference: group index is missing");
26 nextChar = replacement.charAt(cursor);
27 int refNum = -1;
28 if (nextChar == '{') {
29 cursor++;
30 StringBuilder gsb = new StringBuilder();
31 while (cursor < replacement.length()) {
32 nextChar = replacement.charAt(cursor);
33 if (ASCII.isLower(nextChar) ||
34 ASCII.isUpper(nextChar) ||
35 ASCII.isDigit(nextChar)) {
36 gsb.append(nextChar);
37 cursor++;
38 } else {
39 break;
40 }
41 }
42 if (gsb.length() == 0)
43 throw new IllegalArgumentException("named capturing group has 0 length name");
44 if (nextChar != '}')
45 throw new IllegalArgumentException("named capturing group is missing trailing '}'");
46 String gname = String();
47 if (ASCII.isDigit(gname.charAt(0)))
48 throw new IllegalArgumentException("capturing group name {" + gname + "} starts with digit character");
49 if (!parentPattern.namedGroups().containsKey(gname))
50 throw new IllegalArgumentException("No group with name {" + gname + "}");
51 refNum = parentPattern.namedGroups().get(gname);
52 cursor++;
53 } else {
54 // The first number is always a group
55 refNum = (int)nextChar - '0';
56 if ((refNum < 0)||(refNum > 9))
57 throw new IllegalArgumentException("Illegal group reference");
58 cursor++;
59 // Capture the largest legal group string
60 boolean done = false;
61 while (!done) {
java replace方法62 if (cursor >= replacement.length()) {
63 break;
64 }
65 int nextDigit = replacement.charAt(cursor) - '0';
66 if ((nextDigit < 0)||(nextDigit > 9)) { // not a number
67 break;
68 }
69 int newRefNum = (refNum * 10) + nextDigit;
70 if (groupCount() < newRefNum) {
71 done = true;
72 } else {
73 refNum = newRefNum;
74 cursor++;
75 }
76 }
77 }
78 // Append group
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论