Q: How to validate a string that contains characters other than alphabets, digits and some optional characters?
Assumption: Options characters here are: -!@#$%^&*()_+|~-=\\’{
Answer:
String optonalChars = "-!@#$%^&*()_+|~-=\\’{";
String str = "pramod-!@#$%^&*()_+|~-=\\’{]";
for(int i = 0; i< str.length(); i++){
char ch = str.charAt(i);
if(!Character.isAlphabetic(ch) && ! Character.isDigit(ch) && optonalChars.indexOf(ch)<0){
System.out.println("Invalid string");
System.out.println("Invalid char is: " + ch);
break;
}
}
Output:
Invalid string
Invalid char is: ]
Assumption: Options characters here are: -!@#$%^&*()_+|~-=\\’{
Answer:
String optonalChars = "-!@#$%^&*()_+|~-=\\’{";
String str = "pramod-!@#$%^&*()_+|~-=\\’{]";
for(int i = 0; i< str.length(); i++){
char ch = str.charAt(i);
if(!Character.isAlphabetic(ch) && ! Character.isDigit(ch) && optonalChars.indexOf(ch)<0){
System.out.println("Invalid string");
System.out.println("Invalid char is: " + ch);
break;
}
}
Output:
Invalid string
Invalid char is: ]