歡迎您光臨本站 註冊首頁

JDK 7中將支持正則表達式命名捕獲組

←手機掃碼閱讀     火星人 @ 2014-03-10 , reply:0

目前Java的正則表達式不支持命名捕獲組功能,只能通過捕獲組的計數來訪問捕獲組.當正則表達式比較複雜的時候,裡面含有大量的捕獲組和非捕獲組,通過從左至右數括弧來得知捕獲組的計數也是一件很煩人的事情;而且這樣做代碼的可讀性也不好,當正則表達式需要修改的時候也會改變裡面捕獲組的計數.

解決這個問題的方法是通過給捕獲組命名來解決,就像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] -> [x]%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] -> [x]%n", bs, c);
26
27 }

或者

1 System.out.println("0x1234 u 5678".replaceFirst(pStr, "u $ 0x$"));


[火星人 ] JDK 7中將支持正則表達式命名捕獲組已經有627次圍觀

http://coctec.com/docs/java/show-post-62108.html