Plompy
Plompy

Reputation: 379

Check for specific characters in string with regex

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

Answers (2)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

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

V0ldek
V0ldek

Reputation: 10573

Regex is always your friend.

Regex validationRegex = new Regex(@"^[^&""><{}\(\)]*$");

bool IsStringValid(string s) => validationRegex.IsMatch(s);

Upvotes: 2

Related Questions