Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" 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
like image 506
shwetha Avatar asked Jun 10 '14 10:06

shwetha


1 Answers

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 &.

like image 82
anubhava Avatar answered Oct 04 '22 02:10

anubhava