2011-12-12 40 views
1

我想要實現在Java中Java的特殊字符的正則表達式

String[] paramsToReplace = {"email", "address", "phone"}; 

//input URL string 
String ip = "http://www.google.com?name=bob&email=okATtk.com&address=NYC&phone=007"; 

//output URL string 
String op = "http://www.google.com?name=bob&email=&address=&phone="; 

URL中使用正則表達式以下可以包含特殊字符,如%

回答

0

對於上面的示例。您可以使用拆分

String[] temp = ip.split("?name=")[1].split("&")[0]; 
op = temp[0] + "?name=" + temp[1].split("&")[0] +"&email=&address=&phone="; 
1

試試這個表達式:(email=)[^&]+(更換email與數組元素),並用組替換:input.replaceAll("("+ paramsToReplace[i] + "=)[^&]+", "$1");

String input = "http://www.google.com?name=bob&email=okATtk.com&address=NYC&phone=007"; 
String output = input; 
for(String param : paramsToReplace) { 
    output = output.replaceAll("("+ param + "=)[^&]+", "$1"); 
} 
+0

如下這將返回不正確的輸出:http://www.google.com?name=bob&email=& – user1093296

+0

@ user1093296我不t看到任何不正確的輸入。你能指定嗎?在我的測試中,我得到了'http://www.google.com?name = bob&email =&address =&phone =',就像您在文章中所要求的一樣。 – Thomas

+0

http://www.google.com?name=bob&email=& – user1093296

0

像這樣的事情?

private final static String REPLACE_REGEX = "=.+\\&"; 
ip=ip+"&"; 
for(String param : paramsToReplace) { 
    ip = ip.replaceAll(param+REPLACE_REGEX, Matcher.quoteReplacement(param+"=&")); 
} 

P.S.這只是一個概念,我沒有編譯這個代碼。

0

你不需要正則表達式來實現這一目標:

String op = ip; 

for (String param : paramsToReplace) { 
    int start = op.indexOf("?" + param); 
    if (start < 0) 
     start = op.indexOf("&" + param); 
    if (start < 0) 
     continue; 
    int end = op.indexOf("&", start + 1); 
    if (end < 0) 
     end = op.length(); 
    op = op.substring(0, start + param.length() + 2) + op.substring(end); 
} 
+0

感謝您的回答。它適用於大多數情況。但是它會給以下情況提供錯誤的輸出:String [] paramsToReplace = {「email」,「address」,「phone」}; String ip =「http://www.google.address?name=bob&[email protected]&address=NYC&phone=007」; – user1093296

+0

@ user1093296:我應該想到這一點。 :$更新了答案。 – flesk