• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1529
  • Last Modified:

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

1 Solution
To the best of my knowledge (University level of Java), this is the exact way I use Regex (of course I would not use regex for this example though. lol).
ddrudikAuthor Commented:
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.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now