我正在使用动态数据并应用我已覆盖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.
我需要以下关键字的消息:
我写了以下Regex:
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。
任何人都可以帮助我。此外,有没有更清洁的方法来实现它。 仅供参考:我也会捕捉其他类型的数据库错误。
由于
答案 0 :(得分:1)
由于最后一个值接近结尾,你可以匹配到行尾,注意不要与最后一段相匹配:
".... The duplicate key value is (.*)\.$"
答案 1 :(得分:1)
使用您的示例表达式,您似乎尝试匹配Country
而不是dbo.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>
的部分
答案 2 :(得分:0)
^Violation\s+of\s+(.*?)'(.*?)'.*?\((.*)\)
我不知道所有可能的错误是怎样的,但上面的正则表达式将捕获:
Group 1: UNIQUE KEY constraint
Group 2: UK_CountryName_Country
Group 3: America