jbtamares
jbtamares

Reputation: 778

Regex not allowing backslash

I have a problem with my regex for not allowing backslash after the allowed characters. I have tested this through regex testers online and it is working, however when I use it on my c#, it returns true at all cost.

This is my regex : var myRegex = new Regex("^[a-zA-Z0-9]+((([._-][^\/<>()[\\]_.,;:\\s@\"]+)*)|(\".+\"\\\/))$");

My Regex

Input samples:

hello-\world : Negative   
hello\world : Negative  
hello/world : Negative  
hello : Positive

However, this is the result when I implement it in c#

Input samples:

hello-\world : Positive (Which should be negative)
hello\world : Negative
hello/world : Negative
hello : Positive

I can't seem to find what's wrong with negating the backslash. Kinda hard to debug and check why the c# version of the Regex gives a different result.

Thanks for all the feedback.

EDIT: Updated the regex to c#

Upvotes: 0

Views: 330

Answers (1)

Rasmus Hansen
Rasmus Hansen

Reputation: 1573

There was an error in your regex. Wrote some test to correct it:

        var myRegex = new Regex("^[a-zA-Z0-9]+((([._-][^\\/<>()[\\]_.,;:\\s@\"\\\\]+)*)|(\".+\"\\\\/))$");
        Assert.IsFalse(myRegex.IsMatch("hello-\\world"));
        Assert.IsFalse(myRegex.IsMatch("hello\\world"));
        Assert.IsFalse(myRegex.IsMatch("hello/world"));
        Assert.IsTrue(myRegex.IsMatch("hello"));

Your first group allows dash, then didn't disallow backslashes.

Upvotes: 0

Related Questions