0

I am trying to replace a pattern as below: Original :

<a href="#idvalue">welocme</a>

Need to be replaced as :

<a href="javascript:call('idvalue')">welcome</a>

Tried the below approach:

String text = "<a href=\"#idvalue\">welocme</a>";
Pattern linkPattern = Pattern.compile("a href=\"#");
text =  linkPattern.matcher(text).replaceAll("a href=\"javascript:call()\"");

But not able to add the idvalue in between. Kindly help me out. Thanks in advance.

Griffith
  • 3,229
  • 1
  • 17
  • 30
mavlesreennap
  • 71
  • 1
  • 1
  • 2

3 Answers3

1

Try getting the part that might change and you want to keep as a group, e.g. like this:

text = text.replaceAll( "href=\"#(.*?)\"", "href=\"javascript:call('$1')" );

This basically matches and replaces href="whatever" with whatever being caught by capturing group 1 and reinserted in the replacement string by using $1 as a reference to the content of group 1.

Note that applying regex to HTML and Javascript might be tricky (single or double quotes allowed, comments, nested elements etc.) so it might be better to use a html parser instead.

Thomas
  • 87,414
  • 12
  • 119
  • 157
1

how about a simple

text.replaceAll("#idvalue","javascript:call('idvalue')")

for this case only. If you are looking to do something more comprehensive, then as suggested in the other answer, an XML parser would be ideal.

AbtPst
  • 7,778
  • 17
  • 91
  • 172
0

Add a capture group to the matcher regex and then reference the group in the replacemet. I found using the JavaDoc for Matcher, that you need to use '$' instead of '\' to access the capture group in the replacement.

Code:

String text = "<a href=\"#idvalue\">welcome</a>";
System.out.println("input: " + text);       
Pattern linkPattern = Pattern.compile("a href=\"#([^\"]+)\"");
text =  linkPattern.matcher(text).replaceAll("a href=\"javascript:call('$1')\"");
System.out.println("output: " +text);

Result:

input: <a href="#idvalue">welcome</a>
output: <a href="javascript:call('idvalue')">welcome</a>

Tom
  • 1
  • 2