Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a string in C#; is there a cleaner way?

Tags:

c#

.net

parsing

C#, .NET 3.5

This just smells of ugly to me, but I can't think of another way.

Given a string with the format of "Joe Smith (jsmith)" (sans quotes), I'd like to parse out just the 'jsmith' string within the parenthesis. I've come up with this:

private static string DecipherUserName( string user )
{
    if( !user.Contains( "(" ) )
        return user;

    int start = user.IndexOf( "(" );

    return user.Substring( start ).Replace( "(", string.Empty ).Replace( ")", string.Empty );
}

Other than my (un)healthy aversion to RegEx, is there a simpler way to parse out the substring?

Edit: To clarify, the string to parse will always be of: "Joe Smith (jsmith)" (sans quotes).

like image 588
Metro Smurf Avatar asked Apr 07 '09 23:04

Metro Smurf


3 Answers

Regexes are so useful that you'll save yourself a ton of heartache biting the bullet and learning them. Not the whole shebang, just the basics.

One regex that'll work is "\w+\((.*)\)" - jsmith would be in Match.Groups[1].

One easy way to pick up regexes is to find a website that'll let you type in a regex and some text then spit out the matches...

like image 143
Shea Avatar answered Oct 23 '22 19:10

Shea


You shouldn't need the first replace since you can just add 1 to the "(" position.

private static string DecipherUserName (string user) {           
    int start = user.IndexOf( "(" );
    if (start == -1)
        return user;
    return user.Substring (start+1).Replace( ")", string.Empty );
}
like image 9
paxdiablo Avatar answered Oct 23 '22 20:10

paxdiablo


Kind of a hack ... ^^

return user.Substring(user.IndexOf('(') + 1).TrimEnd(')');

If user contains no opening parenthesis, IndexOf() returns -1, we add one, get zero, and SubString() returns the whole string. TrimEnd() will have no effect unless the user's name ends with a closing parenthesis.

If user contains a opening parenthesis, IndexOf() returns its index, we skipp the opening parenthesis by adding one, and extract the rest of the string with Substring(). Finally we remove the closing parenthesis with TrimEnd().

like image 5
Daniel Brückner Avatar answered Oct 23 '22 21:10

Daniel Brückner