2010-09-16 94 views
0

我要找的正則表達式拿到賽爲"HELLO""WORLD"分別當輸入爲以下任一:用於分割字符串正則表達式

"HELLO", "WORLD" 
"HELL"O"", WORLD" 
"HELL,O","WORLD" 

我已經試過幾個組合,但他們都不來適用於所有場景。

我期待有我的C#代碼是這樣執行的東西:

string pattern = Regex Pattern; 
// input here could be any one of the strings given above 
foreach (Match match in Regex.Matches(input, pattern)) 
{ 
    // first iteration would give me Hello 
    // second iteration would give me World 
} 

回答

4

如果你只需要它在你好和世界我建議塞巴斯蒂安的答案。這是一個完美的方法。如果你真的把其他數據放在那裏,並且不想捕獲Hello和World。

下面是另一種解決方案:

^([AZ \ 「\,] +)[\」 \,\ S] +([AZ \「\,] +)$

唯一事情是,這將使HELLO和WORLD與「和」一起迴歸。

然後我們給你做了替換「,並以失敗輸出字符串

例:

//RegEx: ^([A-Z\"\,]+)[\"\,\s]+([A-Z\"\,]+)$ 
    string pattern = "^([A-Z\"\\,]+)[\"\\,\\s]+([A-Z\"\\,]+)$"; 
    System.Text.RegularExpressions.Regex Reg = new System.Text.RegularExpressions.Regex(pattern); 

    string MyInput; 

    MyInput = "\"HELLO\",\"WORLD\""; 
    MyInput = "\"HELL\"O\"\",WORLD\""; 
    MyInput = "\"HELL,O\",\"WORLD\""; 

    string First; 
    string Second; 

    if (Reg.IsMatch(MyInput)) 
    { 
     string[] result; 
     result = Reg.Split(MyInput); 

     First = result[1].Replace("\"","").Replace(",",""); 
     Second = result[2].Replace("\"","").Replace(",",""); 
    } 

第一和第二次將您好,世界

希望這會有所幫助,請告訴我是否需要進一步的幫助

2

試試這個:

Regex.Match(input, @"^WORLD|HELL[""|O|,]?O[""|O|,]$").Success 
+0

這是一個問題的答案,這是許多程序員的問題,他們回答用戶,但用戶不知道如何添加程序員。我的大腦說「42」。 – GvS 2010-09-16 12:16:26