2015-02-09 14 views
0

我有一個輸入字符串:替換正則表達式OCCURENCES

"hello [you], this is [me]" 

我有一個字符串映射到串的函數(硬編碼爲簡單起見):

public String map(final String input) { 
    if ("you".equals(input)) { 
     return "SO"; 
    } else if ("me".equals(input)) { 
     return "Kate"; 
    } 
    ... 
} 

什麼是最通過各自的映射(通過調用map函數給出)替換每個[(.*)?]的便捷方法?

如果我是正確的,你不能使用String.replaceAll()這裏,因爲我們不知道提前更換。

+0

您應該使用'java.util.Map '而不是此函數。 – DennisW 2015-02-09 13:48:51

回答

1

首先,你必須是貪婪的表現。一個適當的表達以在方括號匹配的令牌是\[([^\]]*)\](反斜槓需要加倍爲Java),因爲它避免了去過去右方括號*。我添加了一個捕獲組訪問方括號內的內容爲group(1)

這裏是一個方式做你需要的東西:

Pattern p = Pattern.compile("\\[([^\\]]*)\\]"); 
Matcher m = p.matcher(input); 
StringBuffer bufStr = new StringBuffer(); 
boolean flag = false; 
while ((flag = m.find())) { 
    String toReplace = m.group(1); 
    m.appendReplacement(bufStr, map(toReplace)); 
} 
m.appendTail(bufStr); 
String result = bufStr.toString(); 

Demo.

*您可以使用[.*?],太多,但這種不情願的表達可能會導致回溯。

+1

你的意思'Pattern.compile( 「\\ [^ \\] *] \\]」);',否則你的格局將馬赫' 「你好[你」' – ericbn 2015-02-09 13:50:05

+0

@ericbn謝謝!我在演示時遇到了這個錯誤,所以現在它已經修復了。 – dasblinkenlight 2015-02-09 13:55:55

+0

謝謝。我真的不明白appendReplacement函數。現在我知道了! – 2015-02-09 14:07:52

0

你可以這樣做:

String line = "hello [you], this is [me]"; 

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

while (m.find()) { 
    // m.group(1) contains the text inside [] 
    // line.replace(m.group(1), yourMap.get(m.group(1))); 
    // use StringBuilder to build the new string 
} 
+0

謝謝。這並不能真正回答完整的問題。一旦發現事件(使用'm.group(1)'),我怎樣才能通過它的映射在原始輸入中替換它? – 2015-02-09 13:47:23

+0

@KateDeens我更新了我的答案。 – Maroun 2015-02-09 13:49:12

+0

字符串是不可變的:)'line.replace'不會影響行。 – Pshemo 2015-02-09 13:50:36