I am trying to apply negation on regular expression in .Net. It does not work. When string has valid last name reg ex should not match. For invalid last name it should match. Valid name allows only charecters, spaces, single quote and length between 1-40. Somebody suggested to parse the XML, I don't want to do that. I know there is another way of doing this by removing the negation in reg ex and invert the match condition in code. But I don't want that too. I need pure reg ex solution for this.
Here is my code. That does match the valid last name. But I don't want to match.
string toBevalidated = @"<FirstName>SomeName</FirstName><LastName>Some</LastName><Address1>Addre1</Address1>";
var regex = new Regex(@"<LastName>([^a-zA-Z'\s])|(.{41,})</LastName>");
var match = regex.Match(toBevalidated);
// Check to see if a match was found
if (match.Success)
{
Console.WriteLine("Success");
}
else
{
Console.WriteLine("Failed");
}
EDIT: There are confusion here let me give some example what I intended to to. when last name is valid reg ex should not match. For example below samples should not match the reg ex
case 1
<FirstName>SomeName</FirstName><LastName>Brian</LastName><Address1>Addre1</Address1>
Case 2
<FirstName>SomeName</FirstName><LastName>O'neil</LastName><Address1>Addre1</Address1>
case 3
<FirstName>SomeName</FirstName><LastName>Peter John</LastName><Address1>Addre1</Address1>
When last name is invalid, reg ex should match
case 4
<FirstName>SomeName</FirstName><LastName>Brian123</LastName><Address1>Addre1</Address1>
case 5
<FirstName>SomeName</FirstName><LastName>#Brian</LastName><Address1>Addre1</Address1>
case 6
<FirstName>SomeName</FirstName><LastName>BrianBrianBrianBrianBrianBrianBrianBrianBrianBrian</LastName><Address1>Addre1</Address1>
if you need more information please let me know