1 18 22 package org.apache.roller.util; 23 import org.apache.commons.codec.binary.Hex; 24 25 import java.io.UnsupportedEncodingException ; 26 import java.util.ArrayList ; 27 import java.util.regex.Matcher ; 28 import java.util.regex.Pattern ; 29 30 31 34 public class RegexUtil 35 { 36 public static final Pattern mailtoPattern = Pattern.compile("mailto:([a-zA-Z0-9\\.]+@[a-zA-Z0-9\\.]+\\.[a-zA-Z0-9]+)"); 37 public static final Pattern emailPattern = Pattern.compile("\\b[a-zA-Z0-9\\.]+(@)([a-zA-Z0-9\\.]+)(\\.)([a-zA-Z0-9]+)\\b"); 38 39 public static String encodeEmail(String str) 40 { 41 Matcher mailtoMatch = mailtoPattern.matcher(str); 44 while (mailtoMatch.find()) 45 { 46 String email = mailtoMatch.group(1); 47 String hexed = encode(email); 49 str = str.replaceFirst("mailto:"+email, "mailto:"+hexed); 50 } 51 52 return obfuscateEmail(str); 53 } 54 55 63 public static String obfuscateEmail(String str) 64 { 65 Matcher emailMatch = emailPattern.matcher(str); 66 while (emailMatch.find()) 67 { 68 String at = emailMatch.group(1); 69 str = str.replaceFirst(at, "-AT-"); 71 72 String dot = emailMatch.group(2) + emailMatch.group(3) + emailMatch.group(4); 73 String newDot = emailMatch.group(2) + "-DOT-" + emailMatch.group(4); 74 str = str.replaceFirst(dot, newDot); 76 } 77 return str; 78 } 79 80 89 public static ArrayList getMatches(Pattern pattern, String match, int group) 90 { 91 ArrayList matches = new ArrayList (); 92 Matcher matcher = pattern.matcher(match); 93 while (matcher.find()) 94 { 95 matches.add( matcher.group(group) ); 96 } 97 return matches; 98 } 99 100 107 public static String encode(String email) 108 { 109 StringBuffer result = new StringBuffer (); 110 try { 111 char[] hexString = Hex.encodeHex(email.getBytes("UTF-8")); 112 for (int i = 0; i < hexString.length; i++) { 113 if (i % 2 == 0) { 114 result.append("%"); 115 } 116 result.append(hexString[i]); 117 } 118 } catch (UnsupportedEncodingException e) { 119 return email; 120 } 121 122 return result.toString(); 123 } 124 } 125 | Popular Tags |