开发者

Replacing different substrings using regex

开发者 https://www.devze.com 2023-02-14 21:40 出处:网络
Is it possible to have a regular expression which replaces \"I\" with \"you\" and \"you\" with \"I\"?

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 e开发者_运维问答xtra 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);


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

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号