I have written a small method that extracts certain information from a string. An example of such a string is
"Some text BLA/123/5345/349230498 some more text PNR: 12345678, Name: John, CallName: Peter, TimeStamp: 01.10.2015"
Now I need certain information from this string, e.g. the PNR
, Name
, CallName
, and TimeStamp
(as string
). Right now the method looks like this:
/// <summary>
/// Reads the value of a specified attribute from the log entry.
/// </summary>
/// <param name="identifier">The prefix used in the string (e.g. "Name" in "Name: John").</param>
/// <returns>The value of the attribute (e.g. "John" bei "Name: John".</returns>
private string GetValueFromMessage(string identifier)
{
int index = this.Message.IndexOf(identifier) + identifier.Length + 2;
if (index != -1)
{
char c = this.Message[index];
string result = string.Empty;
while (c != ',')
{
result += c;
index++;
if (index < this.Message.Length)
{
c = this.Message[index];
}
else
{
break;
}
}
return result;
}
return null;
}
Some parts that I don't like about my code, and don't know if they're done correctly:
- It looks too long/not elegant to me. Specifically, I think the loop could be done more efficiently. I tried different loops, also tried with a line of the form
c = this.Message[++index]
, but then I ran into problems at the end of the string. - I want to get rid the double usage of
c = this.Message[index]
somehow. - Is it even good style to
return null
if there is no occurrence of the attribute? (As info: this can happen, but maybe it would be smarter to returnstring.Empty
then?) - Should I use
this.Message
instead of justMessage
when it is a public property of the surrounding class? - I also want to get rid of the
if
statement (and the uglybreak
) inside the loop if possible, but didn't really find a way yet.
Maybe something along the lines of
while (index < this.Message.Length && c != ',')
would work?
( Name: )(.+?)(,)
for "Name" attribute ? – Shivan Dragon Oct 20 '14 at 14:13