Using Back References with String replaceAll method

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:

  1. first create two regular expression for matching all capital letters [A-Z] and all single digits [0-9]
  2. 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.
  3. 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);
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值