2012-05-02 43 views
2

我有一個字符串,看起來是這樣的:「你可以使用推廣到[開始日期+ 30]」。我需要將[ Start Date + 30]佔位符替換爲實際日期 - 這是銷售的開始日期加上30天(或任何其他號碼)。 [Start Date]也可能出現在它自己沒有添加號碼。此外,佔位符內的任何額外空格都應該被忽略,並且不會失敗替換。更換變量佔位符的字符串

什麼是做在Java中的最佳方式是什麼?我想正則表達式尋找佔位符,但不知道如何做解析部分。如果這只是[開始日期]我想用String.replaceAll()方法,但因爲我需要解析的表達和增加的天數,我不能使用它。

+2

一窺MessageFormat.format的javadoc,我想這是在最適合做文本替換的類。 – BigMike

回答

3

您應該使用StringBufferMatcher.appendReplacementMatcher.appendTail

這裏有一個完整的例子:

String msg = "Hello [Start Date + 30] world [ Start Date ]."; 
StringBuffer sb = new StringBuffer(); 

Matcher m = Pattern.compile("\\[(.*?)\\]").matcher(msg); 

while (m.find()) { 

    // What to replace 
    String toReplace = m.group(1); 

    // New value to insert 
    int toInsert = 1000; 

    // Parse toReplace (you probably want to do something better :) 
    String[] parts = toReplace.split("\\+"); 
    if (parts.length > 1) 
     toInsert += Integer.parseInt(parts[1].trim()); 

    // Append replaced match. 
    m.appendReplacement(sb, "" + toInsert); 
} 
m.appendTail(sb); 

System.out.println(sb); 

輸出:

Hello 1030 world 1000. 
+0

出於某種原因,我不得不使用m.group(0)而不是m.group(1)來使其工作,所有想法爲什麼?文檔說m.group(0)是整個模式,實際組從1開始,但實際上它並不起作用。與m.group(1)我得到了「IndexOutOfBoundsException:無組1」。 另外,份[1]包含所以需要過濾掉所述非數字的閉括號作爲此處建議http://stackoverflow.com/questions/4030928/extract-digits-from-a-string-in-java – Alex

+1

在諸如'\表達式[(。*?)\]''到上輸入' 「AB苯並[cd] EF」'將給出' 「苯並[cd]」'在組0 find'一個呼叫(全匹配)和組中的''cd''(組中的東西'(...)',即與'。*?'匹配的部分)。 – aioobe

+0

哎呀,你是對的我忘了在構建正則表達式時添加圓括號,無論哪種方式適用於我。 – Alex