2012-09-27 56 views
2

我有正則表達式的問題。需要正則表達式專家的幫助! 這很簡單,但我無法讓它工作。Java替換特殊字符的正則表達式[

我知道如果我要檢查文本的起點,我應該用^ 和文本的結局,我應該使用$

我想更換[quote]<a>quote</a>

這似乎並不工作..

String test = "this is a [quote]" 
test.replaceAll("^\\[", "<a>"); 
test.replaceAll("\\]$", "</a>"); 

我希望字符串成爲"this is a <a>quote</a>" ..

+0

如果您可以保證沒有嵌套引號,則正則表達式只能用於此目的。對於嵌套引號,您需要更強大的功能(堆棧)。要記住的事情。 – bdares

回答

4

如果您想用對替換[],則需要一次更換它們。

String test = "this [test] is a [quote]"; 
String result = test.replaceAll("\\[([^\\]]+)\\]", "<a>$1</a>"); 
2

^意味着你正在尋找的字符串的開頭的東西。但[未出現在字符串的開頭,因此您不會有匹配項。只要這樣做:

test.replaceAll("\\[", "<a>"); 
test.replaceAll("\\]", "</a>"); 

此外,您不能在原地修改字符串。你將不得不將輸出分配給某個東西。你可以這樣做:

test = test.replaceAll("\\[", "<a>").replaceAll("\\]", "</a>"); 

這就是如果你仍然想使用變量test