Alex Georgievskiy
Alex Georgievskiy

Reputation: 53

How to make a regex to check for other symbols than a given string?

I need to make a regex that checks if an input string contains symbols other than symbols that I have in the charRange string.

given string:

string charRange = 
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;-?! '()$%&\"";

Upvotes: 0

Views: 215

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186698

For a given range and value

string charRange =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;-?! '()$%&\"";

string value = "-7Rt1Vp2RV";

Linq solution (shorter and more readable):

bool hasOutOfRangeChar = value.Any(c => !charRange.Contains(c));

If you insist on regular expressions:

bool hasOutOfRangeChar = !Regex.IsMatch(value, "^[" + Regex.Escape(charRange) + "]*$");

please, notice Regex.Escape since - has a special meaning when within [...] - range form to; e.g. ;-? means any symbol from ; to ?

Upvotes: 1

Dour High Arch
Dour High Arch

Reputation: 21712

If you're just checking whether a string doesn't contain a character in another string, use Linq:

var stringContainsOtherSymbol = !stringToCheck.All(c => stringOfAllowedChars.Contains(c))

Using Regex is just going to trip you up because you have to escape regex metacharacters in stringOfAllowedChars.

Upvotes: 1

Samvel Petrosov
Samvel Petrosov

Reputation: 7706

Here is full example how you should use this :

    string charRange = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;\-?! '()$%&""";
    foreach(Match a in new Regex("[^"+charRange+"]").Matches("-7Rt1Vp2RV"))
    {
        Console.WriteLine(a.Value);
    }

- is special symbol and must be with \. That was the reason you get true.

Upvotes: 2

Related Questions