tags:

views:

80

answers:

2

Hi,

I have a string value and wish to get the engineers name only e.g. in this case "CARL HARRISON".

"{ Engineer = CARL HARRISON, HandHeldAvailability = H, HASHHT = True, HHTSTATUS =  }"

The names can be diffrent lenths but will alway be in the same format.

+5  A: 
string name = s.Split(',')[0].Split('=')[1].Trim();

Explanation: Split by , gives

{ Engineer = CARL HARRISON
_HandHeldAvailability = H
_HASHHT = True
_HHTSTATUS =  }

Taking the first element of this gives

{ Engineer = CARL HARRISON

Split by = gives:

{ Engineer_
_CARL HARRISON

Taking the second element of this gives

_CARL HARRISON

so that Trim gives:

CARL HARRISON

I have replaced leading and trailing spaces by _ to make them clear.

Jason
@Downvoter: Please explain.
Jason
It wasn't me who downvoted, but I think the problem one could see is that this easily breaks if one happens to pass in a "bad" string (should throw an IndexOutOfRangeException). But generally, it's clear and concise.
Michael Stum
You're right that if validation is part of the problem then this isn't the best approach. He asked how to extract the name from the string which I assumed meant that he already knows that the string is properly formatted. Thanks for the comment.
Jason
+6  A: 
string regex = @"{ Engineer = (?<Name>.*), HandHeldAvailability";

string input = "{ Engineer = CARL HARRISON, HandHeldAvailability = H, HASHHT = True, HHTSTATUS =  }";
string engineerName = "";

Match match = Regex.Match(input, regex);
if(match.Success && match.Groups["Name"] != null)
{
    engineerName = match.Groups["Name"].Value;
}

A Regex allows you to verify that the input string matches (Otherwise match.Success will be false) and allows to easily change it in case the input format changes. You can also match the other parts easily as well.

Edit: If you call this function a lot (i.e. in a loop), then you can also compile the Regex:

public class YourDataClass {
    private static Regex regex = new Regex(@"{ Engineer = (?<Name>.*), HandHeldAvailability", RegexOptions.Compiled);

    public string GetNameFromInput(string input) {
        var result = string.Empty;
        Match match = regex.Match(input);
        if(match.Success && match.Groups["Name"] != null)
        {
            result = match.Groups["Name"].Value;
        }
        return result;
    }
}
Michael Stum
Nicely done. Regex is awesome for this stuff.
AboutDev
I (over?)use Regex even for the simplest string matching/manipulation operations now - they become addictive once you learned them :-)
Michael Stum