Wednesday, October 6, 2010

JDK 7 will support the regular expression capture group named



Java regular expression currently do not support named capture group function, can only count by capturing group to access capture group. When the regular expression when the more complex, which contains a large number of capture groups and non-capture group, by the number of brackets from left to right to capture the group's count that is a very annoying thing; and the readability of this code is also well, when the regular expression will change when the need to modify the inside to capture group count.
To solve this problem is to capture the group by name to address, like Python, PHP,. Net, and Perl in these languages as regular expressions. This feature Javaer already looking forward to for many years, and now we have finally been realized in JDK7 b50.

The introduction of named capture groups to support the following:



(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"

Now you can use the regular type like this:

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)

Or

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







Recommended links:



xp won t shut down 3 simple steps how to get



MKV to DivX



DV To AVI



WMV To MOV



No comments:

Post a Comment