You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何自定义正则无法匹配第三个参数为null的searchresult方法?

正则无法匹配目标searchresult函数的原因及修正

问题背景

我需要匹配第三个参数为null或string.Empty的searchresult函数调用,编写了如下正则:

^(.*\.)?searchresult\((?:[^,]*,){2}\s*(null|string\.Empty)\s*(?:,[^,]*){2}\);

预期不匹配的代码行

errorList.Add(new Microsoft.Practices.EnterpriseLibrary.Validation.searchresult("[Validation_MaxLength_ErrorMessage_2000]", staffonlineInquiry, "onlineInquiryResponseInformation", string.Empty, null));
searchresult error = new searchresult("[Validation_notwellLeavecheckReturnToWorkDateYes_ErrorMessage]|[Label_IsnotwellLeavecheckReturnToWorkDate_Text]", target, "notwellLeavecheckReturnToWorkDate", null, null);

预期匹配的代码行

errorList.Add(new Microsoft.Practices.EnterpriseLibrary.Validation.searchresult("[Validation_MaxLength_ErrorMessage_2000]", enquiry, null, string.Empty, null));
searchresult error = new searchresult("[Validation_notwellLeavecheckReturnToWorkDateYes_ErrorMessage]|[Label_IsnotwellLeavecheckReturnToWorkDate_Text]", target, string.Empty, null, null);

但该正则无法匹配符合条件的代码行,原因如下:

问题原因

  • 行尾限制过严:原正则结尾的);要求匹配到此处即结束,但实际目标代码中searchresult调用嵌套在其他方法(如errorList.Add())内,);后还有外层方法的闭合括号等内容,正则未允许后续存在字符,导致无法匹配整行。
  • 参数匹配逻辑有缺陷:[^,]*会匹配任意非逗号字符,但如果参数是包含逗号的字符串(如"a,b,c"),会在字符串内的逗号处提前终止匹配,无法正确识别完整参数。

修正后的正则

针对上述问题,调整后的正则如下:

^(.*\.)?searchresult\((?:(?:"[^"]*"|[^,"])*,){2}\s*(null|string\.Empty)\s*(?:,[^,]*){2}\);.*$
  • 新增.*$允许);后存在任意内容,适配嵌套调用场景;
  • 将[^,]*替换为(?:"[^"]*"|[^,"])*,优先匹配带双引号的完整字符串,避免被字符串内的逗号干扰。

内容的提问来源于stack exchange,提问作者user3508811

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 04:17:52