0

I want to write a Regex which would skip characters like < & >. Reason

Now, to represent this I came across this [^<>] and tried using it in an console application, but it does not work.

[^<>]

Regular expression visualization

Debuggex Demo

string value = "shubh<";
string regEx = "[^<>]";
Regex rx = new Regex(regEx);

if (rx.IsMatch(value))
{
    Console.WriteLine("Pass");
}
else { Console.WriteLine("Fail"); }
Console.ReadLine();

The string 'shubh<' should get failed, but I am not sure why it passes the match. Am I doing something rubbish?

Community
  • 1
  • 1
Shubh
  • 6,693
  • 9
  • 48
  • 83

1 Answers1

3

From Regex.IsMatch Method (String):

Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string.

[^<>] is found in shubh< (the s, the h, etc.).

You need to use the ^ and $ anchors:

Regex rx = new Regex("^[^<>]*$");
if (rx.IsMatch(value)) {
    Console.WriteLine("Pass");
} else {
    Console.WriteLine("Fail");
}

Another solution is to check if < or > is contained:

Regex rx = new Regex("[<>]");
if (rx.IsMatch(value)) {
    Console.WriteLine("Fail");
} else {
    Console.WriteLine("Pass");
}
sp00m
  • 47,968
  • 31
  • 142
  • 252