user1290653
user1290653

Reputation: 775

Match function in Regular expressions being null?

I seem to be getting an error message in visual studio saying

Value cannot be null.
Parameter name: input

when I try doing Match BirthYear2 = Regex.Match(kvpInd2.Value.birth.date, BirthPattern2);

I was wondering it was possible to allow the Match function to produce a null? Basically, I dont mind if the kvpInd2.Value.birth.date doesnt contain the expression

Thank you

Upvotes: 2

Views: 9733

Answers (4)

Ivo
Ivo

Reputation: 8362

Before accessing all that property chain, you'll need to check if no object in the chain is null.

if(kvpInd2 != null && kvpInd2.Value != null && kvpInd2.Value.birth != null && kvpInd2.Value.birth.date!= null) {
    Match BirthYear2 = Regex.Match(kvpInd2.Value.birth.date, BirthPattern2);
    ...
}

Upvotes: 0

Sean Carpenter
Sean Carpenter

Reputation: 7731

The most likely issue here is that kvpInd2.Value.birth.date is null. Regex.Match won't throw an exception if the pattern isn't found, but will throw the exception you're seeing if the input is null.

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726779

In your case, Regex.Match is not producing a null, you are passing it a null as its first parameter.

Exceptions: ArgumentNullException - input or pattern is null.

If you would like to make null inputs valid, you could change your call as follows:

Match BirthYear2 = Regex.Match(kvpInd2.Value.birth.date ?? "", BirthPattern2);

This will return with no match (assuming that BirthPattern2 does not match empty strings) when kvpInd2.Value.birth.date is null, rather than throwing an exception.

Upvotes: 11

aquinas
aquinas

Reputation: 23796

Just check if the value is null before you do your match. Done. Or, am I missing something? Another option, I guess is you could do: kvpInd2.Value.birth.date ?? "". That will treat a null as an empty string which (hopefully) your pattern would not match.

Upvotes: 0

Related Questions