from: http://blog.peterdelahunty.com/2008/08/using-back-references-with-string.html
This is small problem i was facing the other day and couldn't find much information about it on the web so thought i would blog about it.
The problem is how to use back references in Java regular expressions.
The problem is this. Say i have a String like so
"orderM 8orderA 3orderX 2NoReturn "
and i want to turn it into a String like so:
"order M#8 order A#3 orderX #2 NoReturn "
i can do this:
String test = " orderM 8 orderA 3 orderX 2 NoReturn ";
String replaced = test. replaceAll ("([A-Z])([0-9])", " $1#$2 ");
What happens here is:
- first create two regular expression for matching all capital letters [A-Z] and all single digits [0-9]
- Next i then put each of these in a group. using ( ) brackets. The grouping means that the match is remembered and can be referenced by the replace string.
- In the replace string i can then reference the matches via the $n notation where n = the number of the group.
So what happens is: The regular expression processor moves along the string looking for cases of a capital letter next to a digit . When it find them it stores the capital letter in a group 1 and the digit in group 2.
So i want to replace the original match with another string i can.
Also note. The whole expression is automatically added to an implicit group zero 0 that is a group of the whole expression.
String replaced = test. replaceAll ("([A-Z])([0-9])", " '$0' ");
will give
order 'M8' order 'A3' order 'X2' NoReturn
IMPORTANT NOTE:
The javadoc says that you reference back references with '\n' (were n = number) but that is not true. That does not work you need to use '$n'. The javadoc is wrong and needs to be updated.
Pattern javadoc
Hope this helps :)
附上将串中a后一字母大写的正则:
String input = "abcadafghat";
String regex = "a(\\w)";
Matcher m = Pattern.compile(regex).matcher(input);
while (m.find()) {
String temp = m.group();
String uppercase;
uppercase = temp.replaceAll("a(\\w)", "$1").toUpperCase();
input = input.replace(temp, "a" + uppercase);
}
System.out.println(input);