The following class demonstrates basic use of Java's Pattern and Matcher class by adding the rel attribute 'nofollow' to the anchor tags of several links.

*Note, this is for educational purposes only. Pattern, Matcher and Regex are NOT ideal for manipulating HTML in Java.

NoFollow.java


//Adds NoFollow rel attribute to links
//Demonstrates StringBuilder, Pattern, Matcher, Regex

import java.util.regex.*;

public class NoFollow{

private StringBuilder[] links = new StringBuilder[10];
	
//Create some test links
public NoFollow(){
	for(int i=0; i<10; i++){
		links[i] = new StringBuilder("<a href='test."+i+".com'>Test "+i+"</a>");
	}
}

public static void main(String[] args){
	
	NoFollow nf = new NoFollow();
	StringBuilder[] links = nf.getLinks();
		
	//Add 'nofollow' rel attribute
	for(int i=0; i<links.length; i++){
		links[i] = new StringBuilder(nf.addNoFollow(links[i].toString()));
	}		
		
	//display the new link
	for(StringBuilder sb: nf.getLinks()){
		System.out.println(sb);
	}
		
	//already added, will not add again
	String testIsNoFollow = nf.addNoFollow(links[0].toString());
}
	
//Adds nofollow rel attribute to link
public String addNoFollow(String link){
	
	//if its already been added, return
	if(isNoFollow(link)){
		System.out.println("NoFollow already added");
		return link;
	}
	
	Pattern p = Pattern.compile("<a href='(.*?)'");
	Matcher m = p.matcher(link);
	if(m.find()){
		System.out.println("Adding No Follow Tag to: " + m.group(1));
		StringBuilder newLink = 
                 new StringBuilder(m.group(0) + " rel='nofollow'");
		newLink.append(link.substring(m.group(0).length()));
		return newLink.toString();			
	}
	return link;
}
	
//checks to see if the nofollow rel attribute exists or no
public boolean isNoFollow(String link){
	Pattern p = Pattern.compile("nofollow");
	Matcher m = p.matcher(link);
	return m.find();
}
	
//Return all links as StringBuilder array
public StringBuilder[] getLinks(){
	return this.links;
}
}