简体   繁体   中英

Java Regex Multiple Pattern Group Replace

Say I have the following string

String Context = "old1 old2 old3 old4 old5 old6"

I wish to do a pattern: (old2).*(old4)

so word 2 would be in $1 and word4 would be in $2 .

Is there any functions or methods that i can replace the two words strings at the same time? Using only the group variable ( $1 and $2 ) ?

So I could specify that $1 will become new2 and $2 will become new4 . I don't want to have to find the string old2 and old4 and replace it to new2 and new4

Only One Group Needed

If I am understanding, this is what you need:

String replaced = yourString.replaceAll("old2(.*?)old4", "new2$1new4");

Explanation

  • old2 matches literal chars
  • (.*?) lazily matches chars (capturing them to Group 1), up to...
  • old4
  • Replace with new2 , the content of Group 1 and new4

You may consider using a Positive Lookahead here.

String s = "old1 old2 old3 old4 old5 old6";
String r = s.replaceAll("old(?=[24])", "new");
System.out.println(r); //=> "old1 new2 old3 new4 old5 old6"

Lookarounds are zero-width assertions. They don't consume any characters on the string.

This will remove "old" replacing it with "new" asserting that either ( 2 or 4 ) follows..

How about a simple replace

 "old1 old2 old3 old4 old5 old6".replace("old2", "new2").replace("old4", "new4");

of course the original String and the replace target and replace replacement can be variables.

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