Matt Matt - 7 months ago 23
Java Question

Replacing different substrings using regex

Is it possible to have a regular expression which replaces "I" with "you" and "you" with "I"?

If so, please could someone show me an expression? Do I need extra Matcher code, rather than a single regex string?

(I'm desperatly trying to learn regex, but all the resources I find on Google seem to teach it as though you already know it...)

I'm looking for something in this format:

String s = "I love you";
String pattern = "???";
String replacement = "???";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(s);
String newString = m.replaceAll(replacement);
System.out.println(newString);

Answer

Quick and dirty, just so you get the idea. But you may need to improve it to make more robust...

public class IdentityCrisis
{

  public static void main( String[] args )
  {
    String dilemma = "I know you want me to be something I don't want to be unless you prove me it is OK";

    System.out.println(
       dilemma.replaceAll("I", "y-o-u")
              .replaceAll("you", "I")
              .replaceAll("y-o-u", "you")
    );        
  }

}