我正在尝试创建一个函数,当找到至少一个非法字符时,该函数返回一个布尔值true。
我在JAVA 8中测试以下函数并运行正常但在android中返回false,即使字符串中包含非法字符。
首先我尝试这个但在两种环境中都失败了。
boolean HaveIllegalChars(String cmd)
{
String IllegalChars = "[^*;<>]";
boolean result = cmd.matches(IllegalChars);
return result;
}
然后我读了这篇文章Regex doesn't work in String.matches()并更改了正则表达式并开始使用JAVA;所以我在Android应用程序中粘贴相同的字符串,但是当我在真实设备中运行该应用程序时,无法正常工作。
boolean HaveIllegalChars(String cmd)
{
String IllegalChars = ".*[^*;<>].*";
boolean result = cmd.matches(IllegalChars);
return result;
}
知道发生了什么事吗?
修改
我尝试了以下字符串
String illegalStr= "*mmm";
String illegalStr1= "<mmm";
String illegalStr2= ";mmm";
String okStr ="!ABC1";
在JAVA中 illegalStr 在Android中返回true(这就是我想要的)。
在JAVA中 illegalStr1 在Android中返回true(这就是我想要的)。
在JAVA中 illegalStr2 在Android中返回true(这就是我想要的)。
在JAVA中 okStr 在Android false中返回false(这就是我想要的)。
答案 0 :(得分:0)
要判断字符串是否包含您要搜索的任何字符,您可以执行以下任何操作:
// at least one of the characters is one of those
return cmd.matches(".*[*;<>].*");
// all the characters are none of those, then invert
return !cmd.matches("[^*;<>]*");
// Search for one character using Pattern
return Pattern.compile("[*;<>]").matcher(cmd).find();
// Same as second one
return !Pattern.compile("[^*;<>]*").matcher(cmd).matches();