go to previous page   go to home page   go to next page


Yes. You might want to modify the program to do that.

Capture Groups

It is often useful to construct the replacement string out of the pieces of the substring that was matched. For example, say that you have a text where heights are expressed in feet and inches like this: 6'3". You want to modify the text so foot and inches are spelled out: 6 foot 3 inches. This can be done by using capture groups. The following fragment

String old = "Sam is 6'3\" but his girlfriend is 5'2\" in heels." ;

String changed = old.replaceAll( "([0-9])'([0-9])+\"", "$1 foot $2 inches" );

System.out.println( changed );

prints out

Sam is 6 foot 3 inches but his girlfriend is 5 foot 2 inches in heels.  

If part of a regular expression is enclosed in parentheses, then whatever that part matches is captured and can be used later on. The part enclosed by the first set of parentheses is called $1, the part enclosed by the second set is called $2, and so on. So in the regular expression "([0-9])'([0-9])+\"" The first capture group ([0-9]) captures the foot part of the height, and the second capture group ([0-9]) captures the inches.

Say that the stubstring that matches was 6'3" so the first capture group holds the 6 and the second holds the 3. The replacement string

"$1 foot $2 inches" 


"6 foot 3 inches" 

For more on capture groups, see chapter 9.


What does the following print?

String original = "Pi is 3.14159265, but e is 2.718281828";
String fixed    = original.replaceAll( "([0-9]+)\\.([0-9])([0-9])[0-9]*", "$1.$2$3" );
System.out.println( fixed );