Chinaunix首页 | 论坛 | 博客
  • 博客访问: 29612
  • 博文数量: 20
  • 博客积分: 890
  • 博客等级: 准尉
  • 技术积分: 195
  • 用 户 组: 普通用户
  • 注册时间: 2010-01-23 22:48
文章分类

全部博文(20)

文章存档

2010年(20)

我的朋友

分类: 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);
        }
    }
}


阅读(418) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~