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

C #, .NET 3.5

It just smells ugly to me, but I can't think of anything else.

Given a string with the format "Joe Smith (jsmith)" (without quotes), I would like to parse only the string "jsmith" in parenthesis. I came 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 );
}

Besides my (un) healthy disgust for RegEx, is there an easier way to parse a substring?

Edit: To clarify, the parsing line will always contain: "Joe Smith (jsmith)" (without quotes).

+5
source share
6 answers

You do not need the first replacement, since you can simply 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 );
}
+9
source

, , . , .

, , -\w +\((. *) \) "- jsmith Match.Groups [1].

- -, , ...

+20

... ^^

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

user , IndexOf() -1, , , SubString() . TrimEnd() , .

user , IndexOf() , , , SubString(). , TrimEnd().

+5

"Joe Smith (jsmith)", .

private static string DecipherUserName(string user)
{
    string[] names = user.Split(new char[] {'(', ')'});
    return names.Length > 2 ? names[1] : user;
}

"Joe Smith (jsmith)", .

private static string DecipherUserName(string user)
{
    return "jsmith";
}

.

+5

IndexOf -1, , - ...

private static string DecipherUserName( string user )
{           
   int start = user.IndexOf( "(" );

   if (start > -1)
   {
      return user.Substring( start ).Replace( "(", string.Empty ).Replace( ")", string.Empty );
   }
   else
   {
      return user;
   }
}
+2

int start=user.IndexOf('(');
if (start != -1) {
  end = user.IndexOf(')', start);
  return user.Substring(start+1,end-start-1);
} else
  return user;

: IndexOf , Substring, -, , ( , ...)

However, the Daniel L method (using String.Split) can be simpler (but it doesn't work very well with invalid strings and should build a string array).

In general, I suggest that you overcome your aversion to regular expressions, since this situation is exactly what they are intended for :-) ...

+1
source

All Articles