2011-03-06 66 views
1

是否可以使用正則表達式將「我」替換爲「您」和「您」替換爲「I」?使用正則表達式替換不同的子字符串

如果是這樣,請有人給我看一個表達式嗎?我是否需要額外的Matcher代碼,而不是一個正則表達式字符串?

(我desperatly努力學習正則表達式,但我發現在谷歌的資源似乎教它,就好像你已經知道了...)

我在尋找這種格式的東西:

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

回答

2

快速和骯髒,只是讓你明白。但你可能需要改進它,使更強大的...

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

所以這是不可能的一個單一的表達呢?像你這樣做是有道理的,但我需要學習正則表達式= / – Matt 2011-03-06 05:03:16