简体   繁体   中英

Why does Java has a replaceAll(regex, replacement) but replaceAll(regex, regex)?

Java does have this function and Thank you for answering, it's too pity to lose attention on the API for me...

For example:

String strOriginal = "A:B&C@D";

I think there should be a really nice method in java to change it like this:

String strNew = NewReplaceAll("(.*?)\\:(.*?)&(.*?)@(.*?)","\4_\3^\2(\1\2\2\1)");

This can give result like this:

AssertTrue(strNew.equalsWith("D_C^B(ABBA)") );

I think you work under the impression that the second String parameter does not take back-references.

It does.

For instance:

System.out.println("foo123".replaceAll("foo(.+)", "baz$1"));

Output:

baz123

It does accept regex as the replacement, but it uses the "dollar" notation (rather than the "backslash" notation) for back references.

So your example should have been:

String strNew = str.replaceAll("(.*?)\\:(.*?)&(.*?)@(.*?)","$4_$3^$2($1$2$2$1)");

Notice that captured group 1 is referred to as $1 , not \\1 , etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM