问题
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
回答1:
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 andnew4
回答2:
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..
回答3:
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.
来源:https://stackoverflow.com/questions/24815523/java-regex-multiple-pattern-group-replace