2013-05-06 45 views
2

我想使用的格式是這樣的替換文本:如何使用輸出中的輸入部分替換文本?

Text Input: (/ 5 6) + (/ 8 9) - (/ 12 3) 
Pattern: (/ %s1 %s2) 
Replacement: (%s1/%s2) 
Result: (5/6) + (8/9) - (12/3) 

有沒有一種方法可以輕鬆地做到這一點?我查看了Java API,但找不到除字符串格式之外的任何東西(與此類型不匹配)和正則表達式(它們不允許我使用輸入的匹配部分作爲輸出的一部分)

+0

正則表達式可以處理它;請參閱http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html – 2013-05-06 23:08:11

回答

4

試試這個:

String input = "(/ 5 6) + (/ 8 9) - (/ 12 3)"; 
String result = input.replaceAll("\\(/ (\\d+) (\\d+)\\)", "($1/$2)"); 

這是假設你%s羣體是數字,但它可以很容易地擴展爲更復雜的集團模式。

對於更復雜的替代品,你可以在代碼檢查每一個匹配的模式:

import java.util.regex.*; 
Pattern pattern = Pattern.compile("\\(/ (\\d+) (\\d+)\\)"); 
Matcher m = pattern.matcher(input); 
StringBuffer result = new StringBuffer(); 
while (m.find()) 
{ 
    String s1 = m.group(1); 
    String s2 = m.group(2); 
    // either: 
    m.appendReplacement(result, "($1/$2)"); 
    // or, for finer control: 
    m.appendReplacement(result, ""); 
    result.append("(") 
      .append(s1) 
      .append("/") 
      .append(s2) 
      .append(")"); 
    // end either/or 
} 
m.appendTail(result); 
return result.toString(); 

要處理更通用的模式,在@rolfl's answer看這個問題。

3

正則表達式和String.replaceAll(regex, replacement)就是答案。

的正則表達式是不適合心臟佯攻,但你會是這樣的:

String result = input.replaceAll(
      "\\(\\s*(\\p{Punct})\\s+(\\d+)\\s+(\\d+)\\)", 
      "($2 $1 $3)"); 

編輯....阿德里安的答案是「約」和我一樣,也更適合你。我的答案假定'/'字符是任何'標點符號'字符,應該複製到結果中,而不是僅處理'/'。

從技術上講,你可能想要的東西,如[-+/*]更換\p{Punct}(請注意,「 - 」必須始終是第一位的),如果你只想數學運算符。

OK,工作示例:

public static void main(String[] args) { 
     String input = "(/ 5 6) + (/ 8 9) - (/ 12 3)"; 
     String regex = "\\(\\s*(\\p{Punct})\\s+(\\d+)\\s+(\\d+)\\)"; 
     String repl = "($2 $1 $3)"; 
     String output = input.replaceAll(regex, repl); 
     System.out.printf("From: %s\nRegx: %s\nRepl: %s\nTo : %s\n", 
       input, regex, repl, output); 
    } 

產地:

From: (/ 5 6) + (/ 8 9) - (/ 12 3) 
    Regx: \(\s*(\p{Punct})\s+(\d+)\s+(\d+)\) 
    Repl: ($2 $1 $3) 
    To : (5/6) + (8/9) - (12/3) 
+0

您需要轉義所有內斜槓(將'\ s'更改爲'\\ s' ) – FDinoff 2013-05-06 23:22:16

+0

謝謝,修正。 :p Daft me – rolfl 2013-05-06 23:24:25

+0

現在外面的人太多了...應該是兩處斜線處都有斜線。我認爲它應該看起來像這樣。 '\\(\\ S *(\\ p {PUNCT})\\ S +(\\ d +)\\ S +(\\ d +)\\)' – FDinoff 2013-05-06 23:26:50

相關問題