2

假设我有一个字符串

String link = "www.thisisalink.com/tick1=@tick1@&tick2=@tick2@&tick3=@tick3@&tick4=@tick4@";

然后我可以使用

link = replaceFirst("(.+)=@\\1@", "");

让它

link = "www.thisisalink.com/&tick2=@tick2@&tick3=@tick3@&tick4=@tick4@";

但是我想遍历字符串,以获取已替换的内容并将其保存在其他位置,例如链表或数组...结果将是:

String[] result = ["tick1=@tick1@", "tick2=@tick2@", "tick3=@tick3@", "tick4=@tick4@"];
String link = "www.thisisalink.com/&&&";

但是我该怎么做呢?我尝试循环使用

while (link.matches("(.+)=@\\1@")){}

这没有用。

4

2 回答 2

3

您可以使用Pattern Matcher类来遍历您的字符串以查找与您的正则表达式匹配的子字符串。然后要替换已建立的子字符串,您可以使用appednReplacementand appendTail。要获得建立匹配,您可以group()从 Matcher 实例中使用。

这是与您想要的类似的东西

String link = "www.thisisalink.com/tick1=@tick1@&tick2=@tick2@&tick3=@tick3@&tick4=@tick4@";

StringBuffer sb = new StringBuffer();

Pattern p = Pattern.compile("(.+)=@\\1@");
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/&&&
[tick1=@tick1@, tick2=@tick2@, tick3=@tick3@, tick4=@tick4@]
于 2013-08-17T13:49:28.910 回答
1

这会产生您想要的字符串:

public static void main(String[] args)
{
    final String link = "www.thisisalink.com/tick1=@tick1@&tick2=@tick2@&tick3=@tick3@&tick4=@tick4@";
    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/&&&
tick1=@tick1@
tick2=@tick2@
tick3=@tick3@
tick4=@tick4@
于 2013-08-17T13:51:54.873 回答