使用正则表达式提取名称

本文关键字:提取 正则表达式 | 更新日期: 2023-09-27 17:59:28

在我的应用程序中,我需要向用户显示错误发生的确切位置。比如在哪个表和列中。我有下面提到的InnerException

从中,我需要提取表名和列名。有什么简单的方法可以提取它们吗?我知道我们可以使用正则表达式来实现,但我不确定如何实现。表名和列名可以根据错误动态更改。

System.Data.SqlClient.SqlException:INSERT语句与FOREIGN KEY约束"FK_state_name"冲突。冲突发生在数据库"StateDB"、表"dbo.State"、列"State_Name"中。

使用正则表达式提取名称

是的,您可以使用以下正则表达式:

String error = "System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint '"FK_state_name'". The conflict occurred in database '"StateDB'", table '"dbo.State'", column 'State_Name'";
Regex rt = new Regex("table '"([^'"]*)'"");
Match m = rt.Match(error);
string table = m.Groups[1].Value;
Regex rc = new Regex("column '([^']*)'");
m = rc.Match(error);
string column = m.Groups[1].Value;

或者一个完整的程序(你可以在这里执行):

using System;
using System.Text.RegularExpressions;
class Program {
    static void Main() {
        string error = "System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint '"FK_state_name'". The conflict occurred in database '"StateDB'", table '"dbo.State'", column 'State_Name'";
        Regex rt = new Regex("table '"([^'"]*)'"");
        Match m = rt.Match(error);
        string table = m.Groups[1].Value;
        Regex rc = new Regex("column '([^']*)'");
        m = rc.Match(error);
        string column = m.Groups[1].Value;
        Console.WriteLine("table {0} column {1}",table,column);
    }
}

尽管如果这是一个应用程序,但有一些建议:不要向用户显示这样的消息。他们不知道数据库是什么,黑客会发现更容易挖掘出有价值的信息。您最好显示一条类似"出现问题,请稍后再试"的消息。

您应该处理错误Number属性,它本身有很多信息,基于此,您可以使用SqlException的其他属性:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlexception%28v=vs.110%29.aspx

PS。例外情况是不同的,我怀疑这些情况是否有单一的消息模式。这可能是违反约束,也可能是插入的值不正确,缺少插入所需的列,我不会指望消息。

 StringBuilder errorMessages = new StringBuilder();
 catch (SqlException ex)
    {
        for (int i = 0; i < ex.Errors.Count; i++)
        {
            errorMessages.Append("Index #" + i + "'n" +
                "Message: " + ex.Errors[i].Message + "'n" +
                "LineNumber: " + ex.Errors[i].LineNumber + "'n" +
                "Source: " + ex.Errors[i].Source + "'n" +
                "Procedure: " + ex.Errors[i].Procedure + "'n");
        }
    }