Use the String.Split intelligently rather than a RegularExpression. RegeularExpressions are great, but sometimes it will take longer to create the proper Regex than it takes to use a simple String.Split operation.
I like to write and use RegularExpressions. However, they are not a panacea for all parsing problems. I do not consider myself a guru on RegularExpressions, and someone reading this article may be able to quickly create a Regex pattern to solve the problem. I stopped trying after several attempts to parse a fairly complex string of error data and was quickly able to parse it using a simple String.Split operation. Also, be aware that the RegularExpression Engine is many times an overkill for an operation that can be done another way.
The string that I am trying to parse is shown below. It is returned from a web service and contains more information than I want to return to the user. For example, look at the following string.
(Message The 'SSN' attribute has an invalid value according to its data type. An error occurred at (1 1342). Severity Error Exception Line Number 1 Exception Line Position 1342) (Message The required attribute 'STREET_ADDR' is missing. An error occurred at (1 1554). Severity Error Exception Line Number 1 Exception Line Position 1554)
I only want to return, to the user, the data following the "(Message " string, which is the high level error. The details that follow the first period (".") are only confusing to the end user. After several iterations of trying to parse the message with Regexes, I finally created the following simple C# method and it returns only the top level errors (2).
| private string GetTopLevelErrors(string errMsg) { string[] msgs = errMsg.Split(new char[] {'.', ')'}); string retMsg = string.Empty; foreach (string msg in msgs) { if (msg.Trim().StartsWith("(Message ")) retMsg += msg.Replace("(Message ", string.Empty) + ". "; } return retMsg; } |
| Private Function GetTopLevelErrors(ByVal errMsg As String) As String Dim msgs As String() = errMsg.Split(New [Char]() {"."c, ")"c}) Dim retMsg As String = String.Empty For Each msg As String In msgs If msg.Trim.StartsWith("(Message ") Then retMsg &= msg.Replace("(Message ", String.Empty) & ". " End If Next Return retMsg End Function |
| The 'SSN' attribute has an invalid value according to its data type. The required attribute 'STREET_ADDR' is missing. |
| Ask a Question, or give your feedback on my articles or products by going to the KnowDotNet Forum or by clicking on My Blog. | ![]() |