用其输入掩码替换正则表达式(200种)

时间:2013-03-17 17:52:09

标签: java regex

记录:

X 表示任何内容

Y 表示年份

M 表示月份

N 表示数字

A 表示字母

例如:

我从数据库输入的掩码是这样的:

XXXYMXXXXXA

我的意见是:

39JY412345O

我想检查这个输入是有效还是无效但是我无法用掩码检查它,我想用这样的正则表达式替换掩码作为其输入掩码:

 /^.{3}Y[0-9]{1}.{5}[a-zA-Z]{1}$/

我没有正则表达式,我只有输入掩码。我有输入验证,它使用正则表达式来检查有效或无效的输入。我应该用我的输入掩码(200种输入掩码)替换正则表达式,并使用它的正则表达式进行验证

我需要编写一个方法,将输入掩码(例如“XXXYMXXXXXA”)转换为java.lang.regex.Pattern格式的正则表达式(例如“。{3} Y [0-9] { 1}。{5} [A-ZA-Z] {1}“)

这是我的方法代码:(但我希望此解决方案的最佳实践

private String replaceAll(String pattern, String value, String replaceValue) {
    String str = value;
    str = str.replaceAll(pattern, replaceValue.concat("{").concat("1").concat("}"));
    return str;
}

和方法调用:

String anything = "[Xx]";
String alphabet = "[Aa]";
String number = "[Nn]";
String word = getName();

word = replaceAll(anything, word, ".");
word = replaceAll(alphabet, word, "[A-Za-z]");
word = replaceAll(number, word, "[0-9]");

1 个答案:

答案 0 :(得分:0)

假设一般方法,掩码中的一个字符(例如'X')与正则表达式的一部分(例如'.')之间存在映射,并且循环掩码字符导致数字量词(如{3})。

所以我把一个帮助器类和一个简单的测试方法组合在一起,所以也许这是从一开始的。

助手类:

import java.util.HashMap;
import java.util.Map;

public class PatternBuilder {

    protected Map<Character, String> mappings = new HashMap<Character, String>();
    protected boolean caseSensitive = false;

    public PatternBuilder() {
    }

    public PatternBuilder(boolean caseSensitive) {
        this.caseSensitive = caseSensitive;
    }

    public PatternBuilder addDefinition(char input, String mapping) {
        if (this.caseSensitive) {
            this.mappings.put(input, mapping);
        } else {
            this.mappings.put(Character.toLowerCase(input), mapping);
        }
        return this;
    }

    public String buildRegexPattern(String mask) {
        if ((mask == null) || (mask.length() == 0))  {
            return "";
        }
        StringBuilder patternBuffer = new StringBuilder();
        char lastChar = 0;
        int count = 0;
        for (int i = 0; i < mask.length(); i++) {
            char c = mask.charAt(i);
            if (this.caseSensitive == false) {
                c = Character.toLowerCase(c);
            }
            if (c != lastChar) {
                if (count > 0) {
                    String mapped = mappings.get(lastChar);
                    if (mapped == null) {
                        // mapping for char not defined
                        return "";
                    }
                    patternBuffer.append(mapped);
                    patternBuffer.append("{").append(count).append("}");
                }
                lastChar = c;
                count = 1;
            } else {
                count++;
            }
        }
        if (count > 0) {
            String mapped = mappings.get(lastChar);
            if (mapped == null) {
                mapped = ".";
            }
            patternBuffer.append(mapped);
            patternBuffer.append("{").append(count).append("}");
        }
        return patternBuffer.toString();
    }

}

用法:

PatternBuilder patternBuilder = new PatternBuilder()
        .addDefinition('X', ".")
        .addDefinition('Y', "Y")
        .addDefinition('M', "[0-9]")
        .addDefinition('N', "\\d")
        .addDefinition('A', "[a-zA-Z]");
String rePattern = patternBuilder.buildRegexPattern("XxxYMXXXXXA"); // case insensitive, x == X
System.out.println("Pattern: '" + rePattern + "'");
Pattern p = Pattern.compile(rePattern);

String[] tests = new String[]{
    "39JY412345O", // Original, match
    "39JY41234FO", // replaced 5 with F, still matching
    "39JY4123457", // replaced O with 7, no match
    "A9JY4123457"  // replaced 3 with A, no match
};        
for (String s : tests) {
    Matcher m = p.matcher(s);
    System.out.println("Test '" + s + "': " + m.matches());
}

我的输出:

Pattern: '.{3}Y{1}[0-9]{1}.{5}[a-zA-Z]{1}'
Test '39JY412345O': true
Test '39JY41234FO': true
Test '39JY4123457': false
Test 'A9JY4123457': false