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" i.e. 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 &
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With