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

本文探讨了一种更高效的方法,使用正则表达式和Pattern/Matcher类来检查字符串中是否包含非法字符,如~、#等,避免了逐字符遍历的低效方式。介绍了两种方法:Pattern#find()和String#split(),以简化字符串验证过程。
摘要由CSDN通过智能技术生成

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

~, #, @, *, +, %, {, }, , [, ], |, “, ”, \, _, ^

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?

解决方案

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() method will return true, if the given pattern is found in the string, even once.

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;

}

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值