2009-04-07 26 views
5

C#,.NET 3.5解析C#中的字符串;有沒有更清潔的方法?

這對我來說只是一種醜陋的氣味,但我想不出另一種方式。

給定一個格式爲「Joe Smith(jsmith)」(無引號)的字符串,我想解析出括號內的'jsmith'字符串。我想出了這一點:

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); 
} 

其他比我(UN)健康厭惡正則表達式,有一個簡單的解析出子呢?爲了澄清,要解析的字符串總是:「Joe Smith(jsmith)」(sans quotes)。

回答

9

你不應該需要的,因爲你第一次更換隻需添加1至 「(」 位置。一個黑客

private static string DecipherUserName (string user) {   
    int start = user.IndexOf("("); 
    if (start == -1) 
     return user; 
    return user.Substring (start+1).Replace(")", string.Empty); 
} 
2

由於的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; 
    } 
} 
+0

忘記IndexOf將返回-1時,該值不存在。謝謝! – 2009-04-08 02:38:15

20

的正則表達式是如此有用,你會救自己一噸的心痛咬住子彈並學習它們。不是全部shebang,只是基礎知識。

工作的一個正則表達式是「\ w + \((。*)\)」 - jsmith會在Match.Groups [1]中。

一個簡單的方法來拿起正則表達式是要找到一個網站,將讓你在正則表達式和一些文字類型,然後吐出匹配...

+0

+1爲正則表達式,因爲它是正確的工具 – 2009-04-07 23:54:31

+0

沒有明確的要求,paren-enclosed用戶名必須遵循名稱不含空格。 「\(。* \)」應該足夠了。 – James 2009-04-08 00:02:02

+0

正確的工具,但錯誤的RE - 你需要一個處理沒有括號的用戶的情況。做到這一點,我會給你一個投票:-) – paxdiablo 2009-04-08 00:02:39

5

類... ^^

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

如果user不包含左括號,IndexOf()返回-1,我們添加一個,得到零,並且SubString()返回整個字符串。除非用戶的名字以右括號結尾,否則TrimEnd()將不起作用。

如果user包含左括號,IndexOf()返回它的索引,我們通過加上一個來滑動左括號,然後用Substring()提取字符串的其餘部分。最後,我們刪除右邊的括號TrimEnd()

1

我會使用

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

但是,這只是一個外觀上的改變:在使用的IndexOf人物是有點快,並且使用子字符串方法似乎表達更準確地應該怎樣做(和方法是,如果你有多個雙括號的更強大的...)

這就是說,丹尼爾大號的方法(使用String.Split)可能比較簡單(但不與畸形字符串的處理非常好,有構造一個字符串數組)。

總而言之,我建議你克服對正則表達式的厭惡,因爲這種情況正是他們的意圖:-) ...

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"; 
} 

僅用於幽默目的的第二項。

相關問題