2013-08-17 18 views
2

比方說,我有一個字符串ReplaceFirst正則表達式

String link = "www.thisisalink.com/[email protected]@&[email protected]@&[email protected]@&[email protected]@"; 

那麼我可以用

link = replaceFirst("(.+)[email protected]\\[email protected]", ""); 

爲了讓

link = "www.thisisalink.com/&[email protected]@&[email protected]@&[email protected]@"; 

但我想循環雖然字符串,獲取已被替換的內容並將其保存到其他位置,如鏈接列表或數組...結果將爲:

String[] result = ["[email protected]@", "[email protected]@", "[email protected]@", "[email protected]@"]; 
String link = "www.thisisalink.com/&&&"; 

但我該怎麼做?我試着循環使用

while (link.matches("(.+)[email protected]\\[email protected]")){} 

哪個沒有用。

回答

3

您可以使用PatternMatcher類遍歷字符串來查找將匹配您的正則表達式的子字符串。然後要替換建立的子字符串,您可以使用appednReplacementappendTail。要建立匹配,您可以使用匹配實例中的group()

下面是類似的東西你想要什麼

String link = "www.thisisalink.com/[email protected]@&[email protected]@&[email protected]@&[email protected]@"; 

StringBuffer sb = new StringBuffer(); 

Pattern p = Pattern.compile("(.+)[email protected]\\[email protected]"); 
Matcher m = p.matcher(link); 
List<String> replaced = new ArrayList<>(); 

while (m.find()) { 
    m.appendReplacement(sb, ""); 
    replaced.add(m.group()); 
} 
m.appendTail(sb); 
//to replace link with String stored in sb use link=sb.toString(); 
//otherwise link will be unchanged 
System.out.println(sb); 
System.out.println(replaced); 

輸出:

www.thisisalink.com/&&& 
[[email protected]@, [email protected]@, [email protected]@, [email protected]@] 
+0

謝謝:)多數民衆贊成在很好。 –

1

這將產生你想要的字符串:

public static void main(String[] args) 
{ 
    final String link = "www.thisisalink.com/[email protected]@&[email protected]@&[email protected]@&[email protected]@"; 
    final int index = link.indexOf("/") + 1; 

    final String[] result = link.substring(index).split("&"); 
    final String newLink = link.substring(0, index) + repeat("&", result.length -1); 
    System.out.println(newLink); 
    for(final String tick : result) 
    { 
     System.out.println(tick); 
    } 
} 

private static String repeat(final String toRepeat, final int repetitions) 
{ 
    final StringBuilder sb = new StringBuilder(repetitions); 
    for(int i = 0; i < repetitions; i++) 
    { 
     sb.append(toRepeat); 
    } 
    return sb.toString(); 
} 

產地:

www.thisisalink.com/&&& 
[email protected]@ 
[email protected]@ 
[email protected]@ 
[email protected]@ 
+0

謝謝,但我更喜歡其他解決方案......感謝您的努力。 –