如果字符串包含非法字符,则返回Java函数 [英] Java function to return if string contains illegal characters

查看:466
本文介绍了如果字符串包含非法字符,则返回Java函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following characters that I would like to be considered "illegal":

@ * + {} < > [] | \ _ ^

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

我想编写一个检查字符串并确定的方法( true / false )如果该字符串包含这些非法行为:

I'd like to write a method that inspects a string and determines (true/false) if that string contains these illegals:

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

然而,一个简单的匹配(...) 检查是不可行的。我需要方法来扫描字符串中的每个字符,并确保它不是这些字符之一。当然,我可以做一些事情可怕喜欢:

However, a simple matches(...) check isn't feasible for this. I need the method to scan every character in the string and make sure it's not one of these characters. Of course, I could do something horrible like:

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...
    }
}

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

Is there a more elegant/efficient way of accomplishing this?

推荐答案

您可以使用 模式 匹配器 这里上课。您可以将所有已过滤的字符放在字符类中,并使用 匹配#find() 方法,检查您的模式是否以字符串形式提供。

You can make use of Pattern and Matcher class here. You can put all the filtered character in a character class, and use Matcher#find() method to check whether your pattern is available in string or not.

你可以这样做: -

You can do it like this: -

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

find()方法将返回true,如果在字符串中找到给定的模式,甚至一次。

find() method will return true, if the given pattern is found in the string, even once.

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

Another way that has not yet been pointed out is using String#split(regex). We can split the string on the given pattern, and check the length of the array. If length is 1, then the pattern was not in the string.

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

如果 arr.length> 1 ,这意味着该字符串包含模式中的一个字符,这就是它被拆分的原因。已经将 limit = 2 作为 split 的第二个参数传递,因为我们只需单次拆分即可。

If arr.length > 1, that means the string contained one of the character in the pattern, that is why it was splitted. I have passed limit = 2 as second parameter to split, because we are ok with just single split.

这篇关于如果字符串包含非法字符,则返回Java函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆