如何检查一个字符串是否包含另外两个字符串

本文关键字:字符串 包含另 两个 是否 何检查 一个 检查 | 更新日期: 2023-09-27 18:05:41

我有一个保存异常消息的变量。我如何检查异常消息文本是否是这样的:

 var ex.message = "Cannot open server 'abcd' requested by the login";

请注意,服务器名称可以是任何长度?

如何检查一个字符串是否包含另外两个字符串

您不应该使用异常消息来确定出了什么问题。相反,捕获相关的异常类型并在其中进行处理。例如,您可能会使用SqlException:

try
{
    ConnectToDatabase();
}
catch(SqlException ex)
{
    //Now we know a SQL exception has occurred, perhaps check the Number property?
    if(ex.Number == 18456) 
    {
        //Login failed
    }
}
catch(Exception ex)
{
    //General exception handling goes here
}

您可以使用正则表达式来完成此操作

var isMatch = Regex.IsMatch(exceptionMessage, "Cannot open server '[^']+' requested by the login");
ex.message.Contains("Cannot open server") && ex.message.Contains("requested by the login")

使用string.Contains("string")

文档

ex.message.StartsWith("Cannot open server") && ex.message.EndsWith("requested by the login")

如果您已经知道服务器名称,还可以检查中间的内容。

为什么不做得更好,定义自己的自定义异常呢。例如ServerConnectionFailedException

一个有点奇特的解决方案(通过外部方法(:

  public static class Strings {
    public static Boolean ContainsAll(this String source, params String[] toFind) {
      if (null == toFind)
        return true; // or throw an exception
      else if (toFind.Length <= 0)
        return true;
      if (String.IsNullOrEmpty(source))
        return false;
      foreach (var item in toFind)
        if (!source.Contains(item))
          return false;
      return true;
    }
  }
  ...
  var ex.message = "Cannot open server 'abcd' requested by the login";
  if (ex.message.ContainsAll("Cannot open server", "requested by the login")) {
    ...
  }