1

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);

1 Answer 1

2

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")
    );        
  }

}
Sign up to request clarification or add additional context in comments.

1 Comment

So it's not possible to do it with a single expression? It makes sense doing it like you did, but I need to learn regex =/

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.