解決這個問題的方法是通過給捕獲組命名來解決,就像Python, PHP, .Net 以及Perl這些語言裡的正則表達式一樣。這個特性Javaer已經期待了很多年,而現在我們終於在JDK7 b50得到了實現。
新引入的命名捕獲組支持如下:
(1) (?X) to define a named group NAME"
(2) \k to backref a named group "NAME"
(3) <$ to reference to captured group in matcher's replacement str
(4) group(String NAME) to return the captured input subsequence by the given "named group"
現在你可以像這樣使用正則式:
1 String pStr = "0x(?\\p{XDigit}{1,4})\\s++u\\+(?\\p{XDigit}{4})(?:\\s++)?";
2
3 Matcher m = Pattern.compile(pStr).matcher(INPUTTEXT);
4
5 if (m.matches()) {
6
7 int bs = Integer.valueOf(m.group("bytes"), 16);
8
9 int c = Integer.valueOf(m.group("char"), 16);
10
11 System.out.printf("[%x] -> [%04x]%n", bs, c);
12
13 }
14
15 String pStr = "0x(?\\p{XDigit}{1,4})\\s++u\\+(?\\p{XDigit}{4})(?:\\s++)?";
16
17 Matcher m = Pattern.compile(pStr).matcher(INPUTTEXT);
18
19 if (m.matches()) {
20
21 int bs = Integer.valueOf(m.group("bytes"), 16);
22
23 int c = Integer.valueOf(m.group("char"), 16);
24
25 System.out.printf("[%x] -> [%04x]%n", bs, c);
26
27 }
或者
1 System.out.println("0x1234 u+5678".replaceFirst(pStr, "u+$ 0x___FCKpd___2quot;));