如果字符串包含非法字符,则返回 Java 函数

2022-09-02 02:21:03

我有以下字符,我希望被视为“非法”:

~, , , , , , , , , , , , , , , , ,#@*+%{}<>[]|\_^

我想写一个检查字符串并确定(/)该字符串是否包含以下非法项的方法:truefalse

public boolean containsIllegals(String toExamine) {
    return toExamine.matches("^.*[~#@*+%{}<>[]|\"\\_^].*$");
}

但是,简单的检查对此是不可行的。我需要该方法来扫描字符串中的每个字符,并确保它不是这些字符之一。当然,我可以做一些可怕的事情,比如:matches(...)

public boolean containsIllegals(String toExamine) {
    for(int i = 0; i < toExamine.length(); i++) {
        char c = toExamine.charAt(i);

        if(c == '~')
            return true;
        else if(c == '#')
            return true;

        // etc...
    }
}

有没有一种更优雅/更有效的方法来实现这一目标?


答案 1

你可以在这里使用PatternMatcher类。您可以将所有过滤的字符放在一个字符类中,并使用 Matcher#find() 方法来检查您的模式是否在字符串中可用。

你可以这样做: -

public boolean containsIllegals(String toExamine) {
    Pattern pattern = Pattern.compile("[~#@*+%{}<>\\[\\]|\"\\_^]");
    Matcher matcher = pattern.matcher(toExamine);
    return matcher.find();
}

find()如果在字符串中找到给定的模式,则方法将返回 true,即使只有一次。


另一种尚未指出的方法是使用String#split(regex)。。我们可以在给定的模式上拆分字符串,并检查数组的长度。如果长度是 ,则模式不在字符串中。1

public boolean containsIllegals(String toExamine) {
    String[] arr = toExamine.split("[~#@*+%{}<>\\[\\]|\"\\_^]", 2);
    return arr.length > 1;
}

如果 ,则表示字符串包含模式中的一个字符,这就是它被拆分的原因。我已将第二个参数传递给 ,因为我们只需进行单个拆分即可。arr.length > 1limit = 2split


答案 2

我需要扫描字符串中每个字符的方法

如果你必须逐个字符地做,正则表达式可能不是一个好方法。但是,由于“黑名单”上的所有字符的代码都小于128,因此您可以使用一个小数组来执行此操作:boolean

static final boolean blacklist[] = new boolean[128];

static {
    // Unassigned elements of the array are set to false
    blacklist[(int)'~'] = true;
    blacklist[(int)'#'] = true;
    blacklist[(int)'@'] = true;
    blacklist[(int)'*'] = true;
    blacklist[(int)'+'] = true;
    ...
}

static isBad(char ch) {
    return (ch < 128) && blacklist[(int)ch];
}