Link to home
Start Free TrialLog in
Avatar of ddrudik
ddrudikFlag for United States of America

asked on

Java regex replace

As an example code I would like to verify that the code below is technically correct Java code.

The code is meant to take a string:
<a href=abc><a href=abc><a href=abc>

And replace all instances of <a href...> with x<a href...>y

The purpose it serves is to verify I have the correct syntax for regex within Java.  Please make note of the backreference $0 and the doubling of the \ character in the pattern, I want to make sure both are correct for use in Java.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class Module1{
  public static void main(String[] asd){
  String sourcestring = "<a href=abc><a href=abc><a href=abc>";
  Pattern re = Pattern.compile("<a\\s+href=[^>]+>",Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
  Matcher m = re.matcher(sourcestring);
  String result = m.replaceAll("x$0y");
  }
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Ryan_Kempt
Ryan_Kempt
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ddrudik

ASKER

Ryan_Kempt, I can't say I would use it for that purpose either, but I appreciate the vote of confidence in the example code.  Thanks.