Reputation: 379
Suppose I have a group of unwanted characters & " > < { } ( )
and I want to validate that a given string does not contains those characters, for now I wrote function like:
bool IsStringValid(string s){
if(s.Contains("&")| s.Contains(">")...)
return false;
return true;
}
How can I write it more elegant? for example in regex?
Upvotes: 1
Views: 86
Reputation: 34150
bool isValid = !Regex.IsMatch(input, "[&\"><{}()]+");
But however I recommand you do it without regex:
bool isValid = !"&\"><{}()".Any(c=> input.Contains(c));
Upvotes: 3
Reputation: 10573
Regex is always your friend.
Regex validationRegex = new Regex(@"^[^&""><{}\(\)]*$");
bool IsStringValid(string s) => validationRegex.IsMatch(s);
Upvotes: 2