regex - How to find if a string contains "ONLY" Special characters in java -
suppose define string as:
string splchrs = "/-@#$%^&_-+=()" ; string inputstring = getinputstring(); //gets string end user
i want check if string "inputstring" contains only special characters contained in string "splchrs" i.e. want set boolean flag true if inputstring contained characters present in "splchrs"
eg: string inputstring = "#######@"; //set boolean flag=true
and boolean flag set false if contained letters did not contain in "splchrs"
eg: string inputstring = "######abc"; //set boolean flag=false
you can use:
string splchrs = "-/@#$%^&_+=()" ; boolean found = inputstring.matches("[" + splchrs + "]+");
ps: have rearranged characters in splchrs
variable make sure hyphen @ starting avoid escaping. removed redundant (and problematic) hyphen middle of string otherwise give different meaning character class (denoted range).
thanks @alanmoore note character in character class:
^
if it's listed first; ] if it's not listed first; [
anywhere; , &
if it's followed &
.
Comments
Post a Comment