2

I want to replace all links on a HTML page with a defined URL and the original link in the query string.

Here is an example:

"http://www.ex.com abc http://www.anotherex.com" 

Should be replaced by:

"http://www.newex.com?old=http://www.ex.com ABC http://www.newex.com?old=http://www.anotherex.com"

I thought about using replaceAll, but I dont know exactly how to reuse the regex pattern in the replacement.

Quick n Dirty
  • 569
  • 2
  • 7
  • 15

2 Answers2

3

something like

String processed = yourString.replaceAll([ugly url regexp],"http://www.newex.com?old=$0")

$0 being a reference to the main capture group of the regexp. see the documentation for Matcher.appendReplacement

for a worthy regexp, you can have your pick from here for example

Community
  • 1
  • 1
radai
  • 23,949
  • 10
  • 71
  • 115
1

I would go about this by doing something like:

List<String> allMatches = new ArrayList<String>();
Matcher m = Pattern.compile("regex here")
  .matcher(StringHere);
while (m.find()) {
allMatches.add(m.group());
}

for(String myMatch : allMatches)
{
  finalString = OriginalString.replace(myMatch, myNewString+myMatch);
}

I didn't test any of this, but it should give you an idea of how to approach it

Matthew Ertel
  • 198
  • 1
  • 10
  • String.replace() replaces all occurences of a given character with another character - you were probably aiming for replaceAll/replaceFirst? also, Strings being immutable, String.replace*() does not alter the string it was called on, but rather returns a new String. – radai Feb 26 '13 at 20:40
  • Unless I misunderstood the question, since I am looping over every match in the regex the .replace() should correctly replace each item. Good point about saving the return of the replace though. I updated my code to reflect that. Either way, your solution is more elagant/quicker and should be the selected answer! – Matthew Ertel Feb 26 '13 at 20:49