[英]How to find if a string contains “ONLY” Special characters in java
假设我将String定义为:
String splChrs = "/-@#$%^&_-+=()" ;
String inputString = getInputString(); //gets a String from end the user
我想检查String“ inputString ”是否只包含字符串“ splChrs ”中包含的特殊字符,即如果inputString只包含“ splChrs ”中包含的字符,我想将布尔标志设置为true
eg: String inputString = "#######@"; //set boolean flag=true
如果布尔标志包含“ splChrs ”中不包含的任何字母,则将其设置为false
eg: String inputString = "######abc"; //set boolean flag=false
您可以使用:
String splChrs = "-/@#$%^&_+=()" ;
boolean found = inputString.matches("[" + splChrs + "]+");
PS:我已经在splChrs
变量中重新排列了你的字符,以确保连字符开始避免转义。 我还从字符串的中间删除了一个冗余的(并且有问题的)连字符,否则它将赋予字符类不同的含义(表示范围)。
感谢@AlanMoore关于字符类中字符的说明:
^
如果它首先列出; 如果它没有列在第一位; [
任何地方; 并且&
如果紧接着另一个&
。
试试这个,
if(inputString.matches("[" + splChrs + "]+")){
// set bool to true
}else{
// set bool to false
}
不要发明自行车,因为所有这些任务对每个人来说都很常见。 我建议尽可能使用Apache Commons lib: http : //commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#containsOnly%28java.lang。串,%20char []%29
containsOnly
public static boolean containsOnly(String str,char [] valid)
Checks if the String contains only certain characters.
A null String will return false. A null valid character array will return false. An empty String (length()=0) always returns true.
StringUtils.containsOnly(null, *) = false
StringUtils.containsOnly(*, null) = false
StringUtils.containsOnly("", *) = true
StringUtils.containsOnly("ab", '') = false
StringUtils.containsOnly("abab", 'abc') = true
StringUtils.containsOnly("ab1", 'abc') = false
StringUtils.containsOnly("abz", 'abc') = false
Parameters:
str - the String to check, may be null
valid - an array of valid chars, may be null
Returns:
true if it only contains valid chars and is non-null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.