Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Regex for whitelisted characters

Tags:

c#

.net

regex

Consider an algorithm that needs to determine if a string contains any characters outside the whitelisted characters.

The whitelist looks like this:

'-.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÖÜáíóúñÑÀÁÂÃÈÊËÌÍÎÏÐÒÓÔÕØÙÚÛÝßãðõøýþÿ

Note: spaces and apostrophes are needed to be included in this whitelist.

Typically this will be a static method, but it will be converted to an extension method.

private bool ContainsAllWhitelistedCharacters(string input)
{
  string regExPattern="";// the whitelist
  return Regex.IsMatch(input, regExPattern);
}

Considerations:

Thanks for the performance comments to all the answerers. Performance is not an issue. Quality, readability and maintainability is! Less code = less chance for defects, IMO.

Question:

What should this whitelist regex pattern be?

like image 626
p.campbell Avatar asked Aug 20 '09 16:08

p.campbell


2 Answers

Why does it have to be a regex?

private bool ContainsAllWhitelistedCharacters(string input)
{
  string whitelist = "abcdefg...";
  foreach (char c in input) {
    if (whitelist.IndexOf(c) == -1)
      return false;
  }
  return true;
}

No need to jump straight into regexes if you aren't sure how to implement the one you need and you haven't profiled that section of code and found out you need the extra performance.

like image 119
Mark Rushakoff Avatar answered Sep 22 '22 01:09

Mark Rushakoff


You could pattern match using the following:

^([\-\.a-zA-Z ÇüéâäàåçêëèïîíìÄÅÉæÆôöòûùÖÜáíóúñÑÀÁÂÃÈÊËÌÍÎÏÐÒÓÔÕØÙÚÛÝßãðõøýþÿ]+)$

Make it an extension method with:

public static bool IsValidCustom(this string value)
{
    string regExPattern="^([\-\.a-zA-Z ÇüéâäàåçêëèïîíìÄÅÉæÆôöòûùÖÜáíóúñÑÀÁÂÃÈÊËÌÍÎÏÐÒÓÔÕØÙÚÛÝßãðõøýþÿ]+)$";
    return Regex.IsMatch(input, regExPattern);
}

I can't think of an easy way to do a maintainable range with extended characters since the order of the characters is not obvious.

like image 27
Kelsey Avatar answered Sep 23 '22 01:09

Kelsey