0

This should be a fairly simple question, but I seem to be overthinking it.

I have an input that I need to make sure does not have any characters that are not ASCII printable characters (character code 32-127).

string someString = "6244ABº¿º";
var regexPattern = new Regex("^$|[ -~]*");

if (regexPattern.IsMatch(someString))
{
   //invalid format
}

Here's an idea of what I want as inputs and outputs:

Input: AB2RAF@#%$@%  Ouput: Valid (All are within ASCII 32-127)
Input: º¿º234234     Ouput: Invalid (Has 'º' and '¿')
Input: AAABCC        Ouput: Valid

Edit: I think it's the regex that's backwards. It has something to do with the '*'?

ferensilver
  • 341
  • 2
  • 4
  • 17

3 Answers3

4

I would just iterate the characters of your string and check if any is outside your desired range. Something like

private bool IsPrintable(string someString)
{
    foreach(var c in someString)
    {
        if((int)c < 32 || (int)c > 127)
            return false;
    }
    return true;
}
Mats391
  • 1,199
  • 7
  • 12
  • 2
    A simpler but slower version would be `!s.Any(c => c < 32 || c > 127)` or ``s.All(c => c >= 32 && c <= 127)`` – CodesInChaos Jan 10 '17 at 15:10
  • Thanks! This seems to do the trick! I did run into some syntax issues with your code (one extra ')' at the end of the if statement. – ferensilver Jan 10 '17 at 15:25
1

Please try the following:

string someString = "6244ABº¿º";
var regexPattern = new Regex("^$|[^ -~]");

if (regexPattern.IsMatch(someString))
{
   //invalid format
}

I added ^ to negate the character range -~, so any character outside that range will match the expression. I also removed the * as it's not necessary (just a single non-printable character is enough for the string to be invalid).

Wagner DosAnjos
  • 6,304
  • 1
  • 15
  • 29
0

Mats391 is the straight forward answer for your question if you only want the range from 32 to 127. However, if you just want to ensure that no control character is present only (if you want to include Unicode characters, for example), then this might be what you are looking for.

string someString = "6244ABº¿º";
bool isValid = someString.All(i => !Char.IsControl(i));
Ghasan غسان
  • 5,577
  • 4
  • 33
  • 44