2010-04-08 36 views
3

我想更換的Java String.replaceAll正則表達式

網/風格/ clients.html

與Java String.replaceFirst方法的第一個方面,所以我可以得到:

$ {} pageContext.request.contextPath /style/clients.html

我試圖

String test = "web/style/clients.html".replaceFirst("^.*?/", "hello/"); 

這給我:

你好/風格/ clients.html

但是當我做

String test = "web/style/clients.html".replaceFirst("^.*?/", "${pageContext.request.contextPath}/"); 

給我

java.lang.IllegalArgumentException:非法羣組引用

回答

7

我的預感是,由於$是特殊字符,所以它被吹起來了。從the documentation

注意,反斜槓()和美元 替換字符串 符號($)可能導致的結果是不同的 比如果它被視爲 文字替換字符串。美元 標誌可被視爲 捕獲的子序列的引用,如上面描述的 所述,反斜槓用於 替換字符串中的轉義字面字符。

所以,我相信你會需要像

"\\${pageContext.request.contextPath}/" 
1

String test = "web/style/clients.html".replaceFirst("^.*?/", "\\${pageContext.request.contextPath}/");

應該做的伎倆。 $用於regexes中的反向引用

0

$是一個特殊字符,您必須將其轉義。

String test = "web/style/clients.html".replaceFirst("^.*?/", "\\${pageContext.request.contextPath}/"); 
6

沒有可已經逃避所有特殊字符替換Matcher.quoteReplacement()的方法:

String test = "web/style/clients.html".replaceFirst("^.*?/", Matcher.quoteReplacement("${pageContext.request.contextPath}/"));