2011-10-18 67 views
0

我正在使用动态数据并应用唯一密钥和其他数据库级验证,我已覆盖SubmitChanges函数。通过正则表达式提取值

这给了我原来的错误,我能够展示给最终用户。但是,此消息是这样的:

Violation of UNIQUE KEY constraint 'UK_CountryName_Country'. Cannot insert duplicate key in object 'dbo.Country'. The duplicate key value is (America). 
The statement has been terminated. 

我需要的信息的以下关键字:

  1. UNIQUE KEY
  2. UK_CountryName_Country
  3. 美国

我已经写了下面的正则表达式:

System.Text.RegularExpressions.Regex.Split(e.Message.ToString(), "^Violation of (UNIQUE KEY){1} constraint '([a-zA-Z_]*)'. Cannot insert duplicate key in object 'dbo.([a-zA-Z]*)'. The duplicate key value is ") 

我已成功获得#1 &#2,但是#3。

任何人都可以帮助我。另外,有没有更好的方法来实现它。仅供参考:我也会捕获其他类型的数据库错误。

感谢

回答

1

用你的例子exp ression,似乎您试图匹配Countrydbo.Country而不是America,你问,所以我同时在我的表达/代码:

Dim ExpressionText As String = "^Violation of (?<KeyType>.*?) constraint '(?<ConstraintName>[^']*)'\.[^']*'(?<ObjectName>[^']*)'[^(]*\((?<KeyValue>[^)]*)\)" 
Dim SearchText As String = "Violation of UNIQUE KEY constraint 'UK_CountryName_Country'. Cannot insert duplicate key in object 'dbo.Country'. The duplicate key value is (America). " _ 
           & vbCrLf & "The statement has been terminated." 
Dim regex As New System.Text.RegularExpressions.Regex(ExpressionText) 
Dim mc As System.Text.RegularExpressions.Match = regex.Match(SearchText) 

Response.Write(mc.Groups("KeyType").Value)   ' writes UNIQUE KEY 
Response.Write(mc.Groups(1).Value)     ' writes UNIQUE KEY 
Response.Write(mc.Groups("ConstraintName").Value) ' writes UK_CountryName_Country 
Response.Write(mc.Groups(2).Value)     ' writes UK_CountryName_Country 
Response.Write(mc.Groups("ObjectName").Value)  ' writes dbo.Country 
Response.Write(mc.Groups(3).Value)     ' writes dbo.Country 
Response.Write(mc.Groups("KeyValue").Value)   ' writes America 
Response.Write(mc.Groups(4).Value)     ' writes America 

表达的设计是非常宽容的错误的类型消息,因为还有其他可能违反的键约束条件。我无法找到可能的错误的列表,但这里是表达的一个细分:

^Violation of     # Match literal text 
(?<KeyType>.*?) constraint  # Capture the words that come before " constraint" 
'(?<ConstraintName>[^']*)'\. # Capture whatever is inside the single quotes: ' 
[^']*       # Match anything up to the next single quote 
'(?<ObjectName>[^']*)'   # Capture whatever is inside the single quotes 
[^(]*       # Match anything up to the next open parentheses: ( 
\((?<KeyValue>[^)]*)\)   #Capture whatever is inside the parentheses 

,如果你不想使用命名捕获组可以摆脱那种样子?<Something>的部件,并只想使用数字

+0

有没有人告诉你,你是一个很棒的正则表达式生成器?在第一次尝试中取得成功。你还可以指导我学习正则表达式的一些链接。谢谢。 – iMatoria

+0

一个非常好的教程(教我90%的知识正则表达式)在[Regular-Expressions.info](http://www.regular-expressions.info) - 该网站的作者也使一块名为RegexBuddy的软件在模拟和帮助调试各种正则表达式方面非常出色(在各种语言/实现中 - 或者称为“正则表达式”) –

1

由于最后一个值是接近你可以匹配到行的末尾,小心不匹配的最后期限结束:

".... The duplicate key value is (.*)\.$" 
+0

是的,非常真实和不错。我正在寻找一些其他的工作来捕捉这些错误。如果我没有得到它,那么我将它标记为答案。谢谢回答。非常感激。 – iMatoria

0
^Violation\s+of\s+(.*?)'(.*?)'.*?\((.*)\) 

我不知道如何所有可能的错误看起来像但上面的正则表达式会捕获:

Group 1: UNIQUE KEY constraint  
Group 2: UK_CountryName_Country 
Group 3: America