简体   繁体   中英

How to find if a string contains “ONLY” Special characters in java

Suppose I define a String as:

String splChrs      = "/-@#$%^&_-+=()" ;

String inputString = getInputString();  //gets a String from end the user

I want to check if String " inputString " contains ONLY special characters contained in String " splChrs " ie I want to set a boolean flag as true if inputString contained only characters present in " splChrs "

eg:  String inputString = "#######@";  //set boolean flag=true

And boolean flag is set as false if it contained any letters that did not contain in " splChrs "

eg:  String inputString = "######abc"; //set boolean flag=false

You can use:

String splChrs = "-/@#$%^&_+=()" ;
boolean found = inputString.matches("[" + splChrs + "]+");

PS: I have rearranged your characters in splChrs variable to make sure hyphen is at starting to avoid escaping. I also removed a redundant (and problematic) hyphen from middle of the string which would otherwise give different meaning to character class (denoted range).

Thanks to @AlanMoore for this note about character in character class:

^ if it's listed first; ] if it's not listed first; [ anywhere; and & if it's followed immediately by another & .

Try this,

if(inputString.matches("[" + splChrs + "]+")){

// set bool to true
}else{

// set bool to false
}

don't invent bicycle, 'cause all those tasks are common mostly to everyone. I suggest using Apache Commons lib where it's possible: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#containsOnly%28java.lang.String,%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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM