sabisabi
sabisabi

Reputation: 1511

Need some change on this regex

Im checking some strings with my regex and somehow its not perfect. Im not sure why. I would like to allow string with only these characters:

So I thought this regex should be enough:

Regex("[^A-Z0-9.$/+%\\- ]$")

But with some string its not really working. I made a small example:

    static Regex regex = new Regex("[^A-Z0-9.$/+%\\- ]$");

    static void Main()
    {
        string s;

        Console.WriteLine("check: \n");

        s = "?~=) 2313";
        Console.WriteLine(s + ": " +IsValid(s));

        s = "ÄÜÖ";
        Console.WriteLine(s + ": " + IsValid(s));

        s = "Ü~=) 2313";
        Console.WriteLine(s + ": " + IsValid(s));

        s = "Ü 2313";
        Console.WriteLine(s + ": " + IsValid(s));

        s = "~=) 2313 Ü";
        Console.WriteLine(s + ": " + IsValid(s));

        s = "ÜÜÜ";
        Console.WriteLine(s + ": " + IsValid(s));

        s = "~=)";
        Console.WriteLine(s + ": " + IsValid(s));

        s = "THIS--STRING $1234567890$ SHOULD BE VALID.%/ +";
        Console.WriteLine(s + ": " + IsValid(s));

        Console.ReadKey();
    }

    public static bool IsValid(string input)
    {
        if (regex.IsMatch(input)) return false;
        return true;
    }

As output I get:

enter image description here

The 1.,3. and 4. are True, but this is wrong. What is wrong with my regex? Any ideas? Thank you

Upvotes: 1

Views: 82

Answers (3)

Anirudha
Anirudha

Reputation: 32797

It should be

^[A-Z0-9.$/+%\\- ]+$
|                 ||match end of the string
|                 |
|                 |match one or more characters of [A-Z0-9.$/+%\\- ]
|start of the string

You need to use quantifiers like +,* to match multiple characters


Your IsValid Class should be

public static bool IsValid(string input)
    {
        if (regex.IsMatch(input)) return true;
        return false;
    }

Upvotes: 1

user1726343
user1726343

Reputation:

Your regex is matching only one character that is not any of those characters. Your regex should be:

^[A-Z0-9\.$/+% ]+$

Also, use a non-inverted function for your check:

public static bool IsValid(string input)
{
    if (regex.IsMatch(input)) return true;
    return false;
}

Upvotes: 0

jonvuri
jonvuri

Reputation: 5930

Try this regex (Did you mean to include - in your description of allowed characters?):

Regex("^[A-Z0-9.$/+% -]*$")

Upvotes: 1

Related Questions