为什么我的方法不适用于正则表达式?

时间:2013-12-18 12:16:02

标签: java regex

我写过这个java方法:

public boolean checkPatternMatching(String sourceToScan, String searchPattern) {

    boolean patternFounded;

    if (sourceToScan == null) {
        patternFounded = false;
    } else {
        Pattern pattern = Pattern.compile(Pattern.quote(searchPattern),
                Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(sourceToScan);
        patternFounded = matcher.matches();
    }
    return patternFounded;
}

现在我想检查像“A”这样的字符串。像这样的方法调用会返回false值,但为什么?

this.checkPatternMatching(stationShortcuts, "[a-zA-Z]")

1 个答案:

答案 0 :(得分:6)

替换以下

Pattern.quote(searchPattern)

searchPattern

否则模式将按字面匹配(特殊字符将失去意义。)