walkerquickpoint.blog.chinaunix.net
quickpoint
全部博文(20)
2010年(20)
浪花小雨
fanggai
uchihaju
分类: Java
2010-07-10 14:16:30
import java.util.regex.Pattern; /** * RegexpGenerator */ public class RegexpGenerator { public static Pattern generateRegexp(String prototype) { return Pattern.compile(generateRegexpFrom(prototype)); } private static String generateRegexpFrom(String prototype) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < prototype.length(); i++) { char c = prototype.charAt(i); if (Character.isDigit(c)) { stringBuilder.append("\\d"); } else if (Character.isLetter(c)) { stringBuilder.append("\\w"); } else { // falltrought: literal stringBuilder.append(c); } } return stringBuilder.toString(); } private static void test(String prototype) { Pattern pattern = generateRegexp(prototype); System.out.println(String.format("%s -> %s", prototype, pattern)); if (!pattern.matcher(prototype).matches()) { throw new AssertionError(); } } public static void main(String[] args) { String[] prototypes = { "2009/11/12", "I'm a test", "me too!!!", "124.323.232.112", "ISBN 332212" }; for (String prototype : prototypes) { test(prototype); } } }
上一篇:PostgreSQL 快速入门
下一篇:【转】个人开公司的流程,以后用得着
登录 注册