Skip to main content
 首页 » 编程设计

c#之正则表达式中的匹配函数为空

2024年01月13日41think

我似乎在 visual studio 中收到一条错误消息说

Value cannot be null. 
Parameter name: input 

当我尝试做 匹配 BirthYear2 = Regex.Match(kvpInd2.Value.birth.date, BirthPattern2);

我想知道是否可以允许 Match 函数生成空值?基本上,我不介意 kvpInd2.Value.birth.date 是否不包含表达式

谢谢

请您参考如下方法:

在你的例子中,Regex.Match不是生成 null,您是传递 null 作为它的第一个参数。

Exceptions: ArgumentNullException - input or pattern is null.

如果您想让 null 输入有效,您可以按如下方式更改您的调用:

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

当 kvpInd2.Value.birth.date 为 null 时,这将返回无匹配项(假设 BirthPattern2 不匹配空字符串) ,而不是抛出异常。