1 5 package org.roller.util; 6 import org.apache.commons.codec.binary.Hex; 7 8 import java.io.UnsupportedEncodingException ; 9 import java.util.ArrayList ; 10 import java.util.regex.Matcher ; 11 import java.util.regex.Pattern ; 12 13 14 17 public class RegexUtil 18 { 19 public static final Pattern mailtoPattern = Pattern.compile("mailto:([a-zA-Z0-9\\.]+@[a-zA-Z0-9\\.]+\\.[a-zA-Z0-9]+)"); 20 public static final Pattern emailPattern = Pattern.compile("\\b[a-zA-Z0-9\\.]+(@)([a-zA-Z0-9\\.]+)(\\.)([a-zA-Z0-9]+)\\b"); 21 22 public static String encodeEmail(String str) 23 { 24 Matcher mailtoMatch = mailtoPattern.matcher(str); 27 while (mailtoMatch.find()) 28 { 29 String email = mailtoMatch.group(1); 30 String hexed = encode(email); 32 str = str.replaceFirst("mailto:"+email, "mailto:"+hexed); 33 } 34 35 return obfuscateEmail(str); 36 } 37 38 46 public static String obfuscateEmail(String str) 47 { 48 Matcher emailMatch = emailPattern.matcher(str); 49 while (emailMatch.find()) 50 { 51 String at = emailMatch.group(1); 52 str = str.replaceFirst(at, "-AT-"); 54 55 String dot = emailMatch.group(2) + emailMatch.group(3) + emailMatch.group(4); 56 String newDot = emailMatch.group(2) + "-DOT-" + emailMatch.group(4); 57 str = str.replaceFirst(dot, newDot); 59 } 60 return str; 61 } 62 63 72 public static ArrayList getMatches(Pattern pattern, String match, int group) 73 { 74 ArrayList matches = new ArrayList (); 75 Matcher matcher = pattern.matcher(match); 76 while (matcher.find()) 77 { 78 matches.add( matcher.group(group) ); 79 } 80 return matches; 81 } 82 83 90 public static String encode(String email) 91 { 92 StringBuffer result = new StringBuffer (); 93 try { 94 char[] hexString = Hex.encodeHex(email.getBytes("UTF8")); 95 for (int i = 0; i < hexString.length; i++) { 96 if (i % 2 == 0) { 97 result.append("%"); 98 } 99 result.append(hexString[i]); 100 } 101 } catch (UnsupportedEncodingException e) { 102 return email; 103 } 104 105 return result.toString(); 106 } 107 } 108 | Popular Tags |