0

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

2
  • Use java.util.regex with the Matcher. Commented Jul 18, 2014 at 0:16
  • Can you explain more what do you mean by your last sentence "I don't want to have to find the string old2 and old4 and replace it to new2 and new4"? It seems that you want to do exactly what you described here, find old2 and old4 and replace it with new2 and new4. Commented Jul 18, 2014 at 0:20

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

Comments

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..

1 Comment

I am not sure if this is what OP really wants, but +1 since it answers question as it is now.
0

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.

2 Comments

This is possibly error prone solution. What if OP will want to swap old2 and old4 places? By replacing old2 with old4 first time and then replacing old4 with old2 you will end up only with old2, with no old4.
Yes, whilst this is not an idiot proof solution, I feel that for a newbie it is an easy to read and understand solution. I am not sure of the OP java level or his real intent, so whether it is suitable for him or not is not known.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.