是否可以简化这个 try-catch 和 if 逻辑?

Is it possible to simplify this try-catch and if logic?

我有以下代码。它按预期工作,但我只是想知道我是否可以更改其背后的逻辑以使其看起来更简单,因为我认为它是多余的。

它是这样工作的:我获取一些数据,然后尝试通过正则表达式传递它。可能的结果有以下三种:

  1. 数据获取正常。
  2. 已获取数据,但其中不包含数字。所以另一个正则表达式通过了。
  3. 未提取数据。 传递了与 2) 相同的正则表达式。 (这是我认为可以简化或优化的内容)

起初我认为可以有一种方法来检查正则表达式 returns 是否为空而不抛出异常,但是(如果我错了请纠正我)没有这样的方法事情......所以这就是为什么我包括 try/catch。没有它,如果满足第三种情况, IF returns 一个例外,因为它说 m2[0].Groups[1].Captures[0].Value 超出范围,当然(因为它是空的)。

所以...有什么方法可以使它看起来更优化吗? 非常感谢!

string regexString = @"&nbsp;\.\.\.&nbsp;.*?>(.*?)<\/a>";
MatchCollection m2 = Regex.Matches(myInput, regexString, RegexOptions.Singleline);

try
{
    if (m2[0].Groups[1].Captures[0].Value.All(Char.IsDigit) == false)
    {
        regexString = @"page=.*?"">(.*?)</a>\n.*?<a class=""pagebtn""";
        m2 = Regex.Matches(myInput, regexString);
    }
}
catch (ArgumentException)
{
    regexString = @"page=.*?"">(.*?)</a>\n.*?<a class=""pagebtn""";
    m2 = Regex.Matches(myInput, regexString);
}

您可以使用 IsMatch 检查它,如果不匹配,请尝试您的第二个正则表达式,如果不匹配,则没有任何匹配项

Regex normalRegex = new Regex(@"&nbsp;\.\.\.&nbsp;.*?>(.*?)<\/a>", RegexOptions.SingleLine);
Regex secondaryRegex = new Regex(@"page=.*?"">(.*?)</a>\n.*?<a class=""pagebtn""");
int valueFound;
bool numberParsed;

if (normalRegex.IsMatch(myInput)) {
   // your code to check here
   // use int.TryParse to parse your value and add the result to 
   numberParsed = int.TryParse(m2[0].Groups[1].Captures[0].Value, out valueFound);
}
if (!numberParsed) {
    if (secondaryRegex.IsMatch(myInput)) {
        // second code matches
    } else {
        // no match
    }
}

在那种情况下你真的不需要你的 try / catch

我假设对您的问题更准确的描述是您希望解析一个可能存在也可能不存在的整数值,但是如果 Value 您的 m2[0].Groups[1].Captures[0].Value.All(Char.IsDigit) 抛出] 是 null.

然后可以简化为这样的东西:

int parsedValue = 0;
if (m2[0].Success)
{
    var value = m2[0].Groups[1].Captures[0].Value;
    if (!string.IsNullOrWhiteSpace(value))
    {
        if (int.TryParse(value, out parsedValue))
        {
            // do something with parsedValue, or with the fact that the value exists and is an integer
        }
    }
}