繁体   English   中英

使用正则表达式提取名称

[英]Extract name using Regular Expression

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

由此,我需要提取表名和列名。 有没有简单的方法可以提取它们? 我知道我们可以使用正则表达式来做到这一点,但是我不确定该怎么做。 表名和列名可以根据错误动态更改。

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

您应该处理错误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");
        }
    }

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

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);
    }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM