目前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] -> [%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$")); |
评论